From 0bc53a83e0fcd9fe5e32d5a16a3cd398de397187 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 11:58:23 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=9F=20feat:=20Continue=20a=20Subagent'?= =?UTF-8?q?s=20Thread=20as=20a=20Chat=20Beside=20the=20Conversation=20(#18?= =?UTF-8?q?417)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🪟 feat: Continue a Subagent's Thread as a Chat Beside the Conversation * 🪟 fix: Take a Side Chat's Streamed Attachments Where Main Chat's Go What a tool hands back while a side chat's generation runs (search sources, a generated file) reached no handler, so it was missing from the rows and from the app's file, memory and preview caches. The side chat's stream now uses the app's attachment handler. --- client/src/Providers/SideChatHostContext.tsx | 69 +++ client/src/Providers/SubagentsHostContext.tsx | 8 +- .../__tests__/SideChatHostContext.spec.tsx | 167 +++++++ .../__tests__/SubagentsHostContext.spec.tsx | 47 +- .../Chat/Messages/Content/AskUserQuestion.tsx | 20 +- .../AskUserQuestionCollapse.test.tsx | 13 +- .../src/components/Chat/Presentation.test.tsx | 83 +++- client/src/components/Chat/Presentation.tsx | 70 ++- .../services.readCodeInputs.spec.tsx | 27 +- client/src/hooks/Chat/contract.ts | 2 + client/src/hooks/Chat/services.ts | 9 +- client/src/locales/en/translation.json | 3 + client/src/routes/ChatSettings.tsx | 1 + .../routes/__tests__/ChatSettings.spec.tsx | 2 + e2e/specs/mock/subagent-activity.spec.ts | 108 +++++ librechat.example.yaml | 3 + packages/chat/src/components.ts | 1 + packages/chat/src/components/pane/Driven.tsx | 37 ++ .../chat/src/components/pane/Followed.tsx | 59 ++- .../components/side/__tests__/panel.spec.tsx | 427 ++++++++++++++++++ packages/chat/src/components/side/load.ts | 8 + packages/chat/src/components/side/panel.tsx | 293 ++++++++++++ .../subagents/__tests__/panel.spec.tsx | 54 +++ .../chat/src/components/subagents/panel.tsx | 8 + packages/chat/src/react.ts | 4 + packages/chat/src/react/side/host.tsx | 46 ++ packages/chat/src/react/side/state.ts | 29 ++ packages/chat/src/react/subagents/host.tsx | 5 + packages/data-provider/src/config.ts | 5 + .../data-schemas/src/app/interface.spec.ts | 18 + packages/data-schemas/src/app/interface.ts | 1 + 31 files changed, 1592 insertions(+), 35 deletions(-) create mode 100644 client/src/Providers/SideChatHostContext.tsx create mode 100644 client/src/Providers/__tests__/SideChatHostContext.spec.tsx create mode 100644 packages/chat/src/components/pane/Driven.tsx create mode 100644 packages/chat/src/components/side/__tests__/panel.spec.tsx create mode 100644 packages/chat/src/components/side/load.ts create mode 100644 packages/chat/src/components/side/panel.tsx create mode 100644 packages/chat/src/react/side/host.tsx create mode 100644 packages/chat/src/react/side/state.ts diff --git a/client/src/Providers/SideChatHostContext.tsx b/client/src/Providers/SideChatHostContext.tsx new file mode 100644 index 0000000000..6edc5080c2 --- /dev/null +++ b/client/src/Providers/SideChatHostContext.tsx @@ -0,0 +1,69 @@ +import { useCallback, useMemo } from 'react'; +import { dataService } from 'librechat-data-provider'; +import { useFollowChat } from '@librechat/chat/react'; +import { useQueryClient } from '@tanstack/react-query'; +import { createGenerationTransport } from '@librechat/chat'; +import type { FollowedChat, SideChatHost, FollowChatOptions } from '@librechat/chat/react'; +import type { TConversation } from 'librechat-data-provider'; +import useNavigateToConvo from '~/hooks/Conversations/useNavigateToConvo'; +import useAttachmentHandler from '~/hooks/SSE/useAttachmentHandler'; +import { ARTIFACTS_SHEET_MAX_WIDTH } from '~/utils/breakpoints'; +import { useConfiguredFooter } from '~/components/Chat/Footer'; +import useScaledMaxWidth from '~/hooks/useScaledMaxWidth'; +import { useChatTransport } from './ChatTransportContext'; +import { useChatSettings } from './ChatSettingsContext'; +import { fetchStreamStatus } from '~/data-provider'; + +/** + * A conversation of the reader's own as a chat they drive: its messages through the ordinary + * route, and its generations started, streamed and stopped over the transport main chat uses. + */ +function useChat( + { conversationId, endpoint }: Pick, + options?: Pick, +): FollowedChat { + const id = conversationId ?? ''; + const { token } = useChatSettings().auth; + const transport = useChatTransport(); + const generation = useMemo( + () => + createGenerationTransport({ + wire: () => transport.stream({ token }), + getStatus: fetchStreamStatus, + start: (request, options) => transport.start(request, options), + abort: ({ chatId, streamId, generationCreatedAt }) => + transport.abort({ conversationId: chatId, streamId, generationCreatedAt }), + }), + [transport, token], + ); + const loadMessages = useCallback(() => dataService.getMessagesByConvoId(id), [id]); + /** + * What a tool hands back while it runs (search sources, a generated file) arrives beside the + * message it belongs to. It goes where main chat's goes: onto the rows that show it, and into + * the app's file, memory and preview caches. + */ + const onAttachment = useAttachmentHandler(useQueryClient()); + const beside = useMemo(() => ({ onAttachment }), [onAttachment]); + return useFollowChat({ + id, + transport: generation, + loadMessages, + endpoint, + enabled: id !== '', + beside, + onWithdrawn: options?.onWithdrawn, + }); +} + +function useOpenConversation(): (conversation: TConversation) => void { + const { navigateToConvo } = useNavigateToConvo(); + return useCallback((conversation) => navigateToConvo(conversation), [navigateToConvo]); +} + +/** What a side chat reads from the app. */ +export const appSideChatHost: SideChatHost = { + useChat, + useOpenConversation, + useSheetLayout: () => useScaledMaxWidth(ARTIFACTS_SHEET_MAX_WIDTH), + useClearsFooter: useConfiguredFooter, +}; diff --git a/client/src/Providers/SubagentsHostContext.tsx b/client/src/Providers/SubagentsHostContext.tsx index d8eb6c2e79..d25abffef4 100644 --- a/client/src/Providers/SubagentsHostContext.tsx +++ b/client/src/Providers/SubagentsHostContext.tsx @@ -1,11 +1,12 @@ import { useCallback, useMemo, useRef, useState } from 'react'; +import { useSetAtom } from 'jotai'; import { useNavigate } from 'react-router-dom'; import { useQuery } from '@tanstack/react-query'; import { CSSTransition } from 'react-transition-group'; import { createGenerationTransport } from '@librechat/chat'; import { SteerPart, ScrollToBottom } from '@librechat/chat/components'; import { ForkOptions, QueryKeys, dataService } from 'librechat-data-provider'; -import { useFollowChat, setDefaultSubagentsHost } from '@librechat/chat/react'; +import { sideChatAtom, useFollowChat, setDefaultSubagentsHost } from '@librechat/chat/react'; import type { FollowedChat, SubagentsHost, @@ -184,9 +185,14 @@ function useToolCallPart( function useNavigation(): SubagentNavigation { const { navigateToConvo } = useNavigateToConvo(); const navigate = useNavigate(); + const setSideChat = useSetAtom(sideChatAtom); + const sideChat = useChatSettings().config.sideChat === true; return { openConversation: (conversation) => navigateToConvo(conversation), openConversationId: (conversationId) => navigate(`/c/${encodeURIComponent(conversationId)}`), + ...(sideChat && { + openBeside: (conversation, text) => setSideChat({ conversation, text }), + }), }; } diff --git a/client/src/Providers/__tests__/SideChatHostContext.spec.tsx b/client/src/Providers/__tests__/SideChatHostContext.spec.tsx new file mode 100644 index 0000000000..5e0cfff591 --- /dev/null +++ b/client/src/Providers/__tests__/SideChatHostContext.spec.tsx @@ -0,0 +1,167 @@ +import React from 'react'; +import { RecoilRoot } from 'recoil'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryKeys, EModelEndpoint } from 'librechat-data-provider'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { + TFile, + TMessage, + ChatEvent, + ChatStreamRequest, + ChatTransportOptions, +} from 'librechat-data-provider'; +import type { Transport } from '~/hooks/Chat/contract'; +import { ChatTransportContext, defaultChatTransport } from '../ChatTransportContext'; + +const mockMessages = jest.fn(); +jest.mock('librechat-data-provider', () => { + const actual = jest.requireActual('librechat-data-provider'); + return { + ...actual, + dataService: { + ...actual.dataService, + getMessagesByConvoId: (...args: unknown[]) => mockMessages(...args), + }, + }; +}); + +const mockStreamStatus = jest.fn(); +jest.mock('~/data-provider/SSE/queries', () => ({ + ...jest.requireActual('~/data-provider/SSE/queries'), + fetchStreamStatus: (...args: unknown[]) => mockStreamStatus(...args), +})); + +const { appSideChatHost } = jest.requireActual('~/Providers/SideChatHostContext'); + +const conversation = { conversationId: 'side-conversation', endpoint: EModelEndpoint.agents }; + +const asked: TMessage = { + messageId: 'user-1', + conversationId: 'side-conversation', + parentMessageId: '00000000-0000-0000-0000-000000000000', + isCreatedByUser: true, + text: 'Make a chart.', +} as TMessage; + +/** The app's transport with a wire the test drives, and a start and stop it can see. */ +function createTransport() { + const attachments: Array<{ request: ChatStreamRequest; options: ChatTransportOptions }> = []; + const start = jest.fn(); + const abort = jest.fn(async () => ({ success: true })); + const transport: Transport = { + ...defaultChatTransport, + stream: () => ({ + send: () => undefined, + reconnectToStream(request, options) { + attachments.push({ request, options }); + return { closed: false }; + }, + }), + start, + abort, + }; + return { transport, attachments, start, abort }; +} + +const setup = () => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const harness = createTransport(); + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + + + {children} + + + + ); + const view = renderHook(() => appSideChatHost.useChat(conversation), { wrapper }); + return { ...view, ...harness, client }; +}; + +describe("the app's side chat host", () => { + beforeEach(() => { + mockMessages.mockReset(); + mockStreamStatus.mockReset(); + }); + + it('reads the conversation through the ordinary messages route, as a list', async () => { + mockStreamStatus.mockResolvedValue({ active: false }); + mockMessages.mockResolvedValue([asked]); + + const { result } = setup(); + + await waitFor(() => expect(result.current.messages).toEqual([asked])); + expect(mockMessages).toHaveBeenCalledWith('side-conversation'); + expect(result.current.hasEarlier).toBe(false); + }); + + it('puts what a tool hands back while it runs into the app, as main chat does', async () => { + mockStreamStatus.mockResolvedValue({ + active: true, + streamId: 'side-conversation', + createdAt: 2000, + generationProtocolVersion: 2, + }); + mockMessages.mockResolvedValue([asked]); + const { attachments, client } = setup(); + await waitFor(() => expect(attachments).toHaveLength(1)); + const emit = (event: ChatEvent) => act(() => attachments[0].options.onEvent(event)); + + emit({ type: 'open' }); + emit({ + type: 'created', + data: { created: true, message: asked, turn: { responseMessageId: 'response-1' } }, + } as ChatEvent); + emit({ + type: 'attachment', + data: { + file_id: 'file-1', + filename: 'chart.png', + filepath: '/images/user/chart.png', + type: 'image/png', + messageId: 'response-1', + toolCallId: 'call-1', + conversationId: 'side-conversation', + }, + } as unknown as ChatEvent); + + /** The app's own file list learns of it, which only the app's handler does. */ + await waitFor(() => + expect(client.getQueryData([QueryKeys.files])).toEqual([ + expect.objectContaining({ file_id: 'file-1', filename: 'chart.png' }), + ]), + ); + }); + + it('stops a generation through the app, by its conversation and the stream it names', async () => { + mockStreamStatus.mockResolvedValue({ + active: true, + streamId: 'side-conversation', + createdAt: 2000, + generationProtocolVersion: 2, + }); + mockMessages.mockResolvedValue([asked]); + const { result, attachments, abort } = setup(); + await waitFor(() => expect(attachments).toHaveLength(1)); + act(() => attachments[0].options.onEvent({ type: 'open' })); + act(() => + attachments[0].options.onEvent({ + type: 'created', + data: { created: true, message: asked, turn: { responseMessageId: 'response-1' } }, + } as ChatEvent), + ); + await waitFor(() => expect(result.current.status).not.toBe('ready')); + + act(() => { + void result.current.stop().catch(() => undefined); + }); + + await waitFor(() => expect(abort).toHaveBeenCalledTimes(1)); + expect(abort).toHaveBeenCalledWith({ + conversationId: 'side-conversation', + streamId: 'side-conversation', + generationCreatedAt: 2000, + }); + }); +}); diff --git a/client/src/Providers/__tests__/SubagentsHostContext.spec.tsx b/client/src/Providers/__tests__/SubagentsHostContext.spec.tsx index 34a27bd3cd..aa94d563db 100644 --- a/client/src/Providers/__tests__/SubagentsHostContext.spec.tsx +++ b/client/src/Providers/__tests__/SubagentsHostContext.spec.tsx @@ -1,6 +1,10 @@ -import { renderHook } from '@testing-library/react'; +import { Provider, createStore } from 'jotai'; +import { sideChatAtom } from '@librechat/chat/react'; import { ForkOptions } from 'librechat-data-provider'; +import { act, renderHook } from '@testing-library/react'; import type { TConversation } from 'librechat-data-provider'; +import type { ReactNode } from 'react'; +import { ChatSettingsContext, defaultChatSettings } from '../ChatSettingsContext'; import { appSubagentsHost } from '../SubagentsHostContext'; const mockThreadRefetch = jest.fn(); @@ -129,6 +133,47 @@ describe('appSubagentsHost writes and navigation', () => { result.current.openConversation(conversation); expect(mockNavigateToConvo).toHaveBeenCalledWith(conversation); }); + + it('offers a place beside the conversation only where the deployment keeps side chats on', () => { + const conversation: TConversation = { + conversationId: 'continued-chat', + title: 'Continued', + endpoint: null, + createdAt: '2026-11-03T00:00:00.000Z', + updatedAt: '2026-11-03T00:00:00.000Z', + }; + const store = createStore(); + const withSettings = (sideChat: boolean | undefined) => + function Wrapper({ children }: { children: ReactNode }) { + return ( + + + {children} + + + ); + }; + + /** Off, or not answered yet: the continuation navigates, as it always has. */ + for (const sideChat of [false, undefined]) { + const closed = renderHook(() => appSubagentsHost.useNavigation(), { + wrapper: withSettings(sideChat), + }); + expect(closed.result.current.openBeside).toBeUndefined(); + } + + const open = renderHook(() => appSubagentsHost.useNavigation(), { + wrapper: withSettings(true), + }); + act(() => open.result.current.openBeside?.(conversation, 'Carry on.')); + expect(store.get(sideChatAtom)).toEqual({ conversation, text: 'Carry on.' }); + expect(mockNavigateToConvo).not.toHaveBeenCalled(); + }); }); describe('appSubagentsHost layout', () => { diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx index 2b6310b6a7..ca05f8b4cc 100644 --- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx +++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useMemo, useContext } from 'react'; import { AskUserQuestion as Question } from '@librechat/chat/components'; import type { ComponentProps } from 'react'; import { useApprovalContext, useResumeSubmit } from './ApprovalContext'; @@ -7,6 +7,8 @@ import { ChatContext } from '~/Providers/ChatContext'; type QuestionProps = ComponentProps; +const keepInCard = (): void => undefined; + /** The app's ask card: answer mode, resume, and the draft the approval host keeps. */ export default function AskUserQuestion( props: Omit< @@ -14,8 +16,20 @@ export default function AskUserQuestion( 'answerMode' | 'submitAskAnswer' | 'getAskAnswerDraft' | 'setAskAnswerDraft' >, ) { - const conversationId = useContext(ChatContext)?.conversation?.conversationId; - const answerMode = useAskAnswerMode(conversationId); + const chat = useContext(ChatContext); + const conversationId = chat?.conversation?.conversationId; + const mode = useAskAnswerMode(conversationId); + /** + * Moving a question into the composer hands it to the main chat's form. A conversation in any + * other pane has no composer that can take it, so there the question stays in its card. + */ + const answerMode = useMemo( + () => + (chat?.index ?? 0) === 0 + ? mode + : { ...mode, collapsed: false, popoverVisible: false, expand: keepInCard }, + [chat, mode], + ); const { getAskAnswerDraft, setAskAnswerDraft } = useApprovalContext(); const { submitAskAnswer } = useResumeSubmit(); return ( diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx index 6695e1f181..5b66a90545 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx @@ -61,12 +61,12 @@ function ComposerProbe() { ); } -const renderPause = () => +const renderPause = (pane?: number) => render( { }; }); + it('stays in its card in a pane that is not the main chat, which has no composer to take it', () => { + renderPause(3); + + expect(screen.queryByLabelText('Answer from the message box')).not.toBeInTheDocument(); + expect( + screen.getByText('North star or full funnel?').closest('[aria-hidden="true"]'), + ).toBeNull(); + }); + it('starts in the chat card and leaves the composer free', () => { renderPause(); diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx index 07272e0dd2..0b099ca83a 100644 --- a/client/src/components/Chat/Presentation.test.tsx +++ b/client/src/components/Chat/Presentation.test.tsx @@ -3,7 +3,7 @@ import { useSetAtom } from 'jotai'; import { RecoilRoot, useSetRecoilState } from 'recoil'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; -import { activeSubagentPanel, isSubmittingFamily } from '@librechat/chat/react'; +import { sideChatAtom, activeSubagentPanel, isSubmittingFamily } from '@librechat/chat/react'; import type { TConversation } from 'librechat-data-provider'; import type { JotaiStore } from 'test/harness'; import type { Artifact } from '~/common'; @@ -29,6 +29,8 @@ const mockArtifactPanelLabel = 'Artifact panel loaded'; const mockOpenArtifactLabel = 'Open Artifact'; const mockChildPanelLabel = 'Child activity panel loaded'; const mockOpenChildLabel = 'Open Child Activity'; +const mockSideChatLabel = 'Side chat loaded'; +const mockOpenSideChatLabel = 'Open Side Chat'; const mockSelectAgentConversationLabel = 'Select Agent Conversation'; const mockStartAgentRunLabel = 'Start Agent Run'; const mockUseParentSubagentsQuery = jest.fn( @@ -58,6 +60,18 @@ jest.mock('@librechat/chat/components', () => { ...jest.requireActual( '@librechat/chat/components', ), + loadSideChatPanel: () => + Promise.resolve({ + default: function MockSideChatPanel() { + const parent = useParentSubagents(); + return ( + + ); + }, + }), loadSubagentThreadPanel: () => Promise.resolve({ default: function MockSubagentThreadPanel() { @@ -165,6 +179,26 @@ const OpenSubagentPanel = ({ durable = true }: { durable?: boolean }) => { ); }; +const OpenSideChat = () => { + const setConversation = useSetRecoilState(store.conversationByIndex(0)); + const setSideChat = useSetAtom(sideChatAtom); + const open = () => { + setConversation({ conversationId: 'parent-conversation' } as TConversation); + setSideChat({ + conversation: { + conversationId: 'side-conversation', + endpoint: 'agents', + agent_id: 'agent-1', + } as TConversation, + }); + }; + return ( + + ); +}; + const SelectAgentConversation = () => { const setConversation = useSetRecoilState(store.conversationByIndex(0)); return ( @@ -364,4 +398,51 @@ describe('Presentation Artifact loading', () => { expect(detachedDocument.body.textContent).toContain(mockArtifactPanelLabel), ); }); + + it('shows a side chat beside the conversation, with child activity read for its own conversation', async () => { + renderPresentation( + + + + + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: mockOpenSideChatLabel })); + + expect(await screen.findByText(mockSideChatLabel)).toBeInTheDocument(); + /** Children its agent dispatches belong to the side conversation, not the one beside it. */ + expect(screen.getByTestId('side-parent')).toHaveTextContent('side-conversation'); + expect(mockUseParentSubagentsQuery).toHaveBeenCalledWith( + 'side-conversation', + { enabled: true }, + false, + ); + + /** One panel at a time: a child's activity opened afterwards takes its place. */ + fireEvent.click(screen.getByRole('button', { name: mockOpenChildLabel })); + expect(await screen.findByText(mockChildPanelLabel)).toBeInTheDocument(); + expect(screen.queryByText(mockSideChatLabel)).not.toBeInTheDocument(); + }); + + it('closes the side chat when the conversation it sits beside changes', async () => { + renderPresentation( + + + + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: mockOpenSideChatLabel })); + expect(await screen.findByText(mockSideChatLabel)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: mockSelectAgentConversationLabel })); + await waitFor(() => expect(screen.queryByText(mockSideChatLabel)).not.toBeInTheDocument()); + }); }); diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx index a76bbf492c..d996914a53 100644 --- a/client/src/components/Chat/Presentation.tsx +++ b/client/src/components/Chat/Presentation.tsx @@ -3,14 +3,18 @@ import { useRecoilValue } from 'recoil'; import { useAtomValue, useSetAtom } from 'jotai'; import { EModelEndpoint } from 'librechat-data-provider'; import { - activeSubagentPanel, + sideChatAtom, + SIDE_CHAT_PANE, useIsSubmitting, + activeSubagentPanel, + SideChatHostProvider, ParentSubagentsProvider, } from '@librechat/chat/react'; import useArtifactsRegistryLifetime from '~/hooks/Artifacts/useArtifactsRegistryLifetime'; import { MessageSurfaceContext } from '~/components/Chat/Messages/ui/surface'; import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper'; import UndockedArtifacts from '~/components/Artifacts/UndockedArtifacts'; +import { appSideChatHost } from '~/Providers/SideChatHostContext'; import { artifactsUndocked } from '~/components/Artifacts/state'; import { EditorProvider, ArtifactsProvider } from '~/Providers'; import { SidePanelGroup } from '~/components/SidePanel'; @@ -29,6 +33,13 @@ const SubagentThreadPanel = lazyWithRecovery(() => ]).then(([panel]) => panel), ); +const SideChatPanel = lazyWithRecovery(() => + Promise.all([ + import('@librechat/chat/components').then((module) => module.loadSideChatPanel()), + import('~/components/Chat/Messages/hosts'), + ]).then(([panel]) => panel), +); + export default function Presentation({ children, routePending = false, @@ -54,6 +65,14 @@ export default function Presentation({ const selectedSubagent = useAtomValue(activeSubagentPanel); const setSelectedSubagent = useSetAtom(activeSubagentPanel); const resetSelectedSubagent = useCallback(() => setSelectedSubagent(null), [setSelectedSubagent]); + const sideChat = useAtomValue(sideChatAtom); + const isSideChatSubmitting = useIsSubmitting(SIDE_CHAT_PANE); + const setSideChat = useSetAtom(sideChatAtom); + const closeSideChat = useCallback(() => setSideChat(null), [setSideChat]); + const takeSideChatText = useCallback( + () => setSideChat((current) => current && { conversation: current.conversation }), + [setSideChat], + ); const previousConversationIdRef = useRef(null); useArtifactsRegistryLifetime(conversationId); @@ -70,8 +89,19 @@ export default function Presentation({ previousConversationIdRef.current = next; if (previous != null && previous !== next) { setSelectedSubagent((current) => (current?.durable == null ? null : current)); + /** A side chat sits beside the conversation it was opened from, and leaves with it. */ + setSideChat(null); } - }, [conversationId, setSelectedSubagent]); + }, [conversationId, setSelectedSubagent, setSideChat]); + + useEffect(() => () => setSideChat(null), [setSideChat]); + + /** One panel at a time: a child's activity opened after the side chat takes its place. */ + useEffect(() => { + if (selectedSubagent != null) { + setSideChat(null); + } + }, [selectedSubagent, setSideChat]); const { data: startupConfig, isSuccess: hasStartupConfig } = useGetStartupConfig(); @@ -106,10 +136,14 @@ export default function Presentation({ * slot. Undocked, the artifacts pane is in its own window and the side panel * is free, so a child-activity panel opened there must survive. */ useEffect(() => { - if (!isUndocked && artifactsElement != null && selectedSubagent != null) { + if (isUndocked || artifactsElement == null) { + return; + } + if (selectedSubagent != null) { resetSelectedSubagent(); } - }, [artifactsElement, isUndocked, resetSelectedSubagent, selectedSubagent]); + closeSideChat(); + }, [artifactsElement, closeSideChat, isUndocked, resetSelectedSubagent, selectedSubagent]); const subagentElement = useMemo(() => { if ( @@ -128,9 +162,35 @@ export default function Presentation({ ); }, [conversationId, selectedSubagent]); + const sideChatElement = useMemo(() => { + if (sideChat == null) { + return null; + } + const { conversationId: sideConversationId, endpoint, agent_id } = sideChat.conversation; + return ( + + {/* Children the side conversation's agent dispatches are its own, not the main one's. */} + + + + + + + ); + }, [closeSideChat, isSideChatSubmitting, sideChat, takeSideChatText]); + /* Undocked, the pane renders into its own window: the side panel gives its * width back to the conversation instead of holding an empty column. */ - const panelElement = (isUndocked ? null : artifactsElement) ?? subagentElement; + const panelElement = (isUndocked ? null : artifactsElement) ?? subagentElement ?? sideChatElement; return ( diff --git a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx index 64edce2639..74897495e5 100644 --- a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx +++ b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx @@ -12,6 +12,8 @@ type ApprovalInputs = Omit; const mockReadWorkspaceInputs = jest.fn(); const mockReadApprovalInputs = jest.fn(); const mockGetLatestConversation = jest.fn(() => null); +/** The comparison conversation each code hook was handed on the last render. */ +const mockComparisons: { workspace?: unknown; approval?: unknown } = {}; jest.mock('react-router-dom', () => ({ useNavigate: () => jest.fn() })); jest.mock('~/hooks/Files/useSetFilesToDelete', () => () => jest.fn()); @@ -20,11 +22,13 @@ jest.mock('~/Providers/AgentsMapContext', () => ({ useAgentsMapContext: () => ({ jest.mock('~/hooks/Conversations/useGetConversation', () => () => mockGetLatestConversation); /** Each render's reader closes over that render's values, as the real hooks' readers do, so an * adapter holding a reader from an earlier render keeps returning the earlier values. */ -jest.mock('~/hooks/Agents/useCodeWorkspace', () => () => { +jest.mock('~/hooks/Agents/useCodeWorkspace', () => (_conversation: unknown, added: unknown) => { + mockComparisons.workspace = added; const rendered = mockReadWorkspaceInputs(); return { mode: undefined, readInputs: () => rendered }; }); -jest.mock('~/hooks/Agents/useCodeApprovalMode', () => () => { +jest.mock('~/hooks/Agents/useCodeApprovalMode', () => (_conversation: unknown, added: unknown) => { + mockComparisons.approval = added; const rendered = mockReadApprovalInputs(); return { readInputs: () => rendered }; }); @@ -95,6 +99,25 @@ describe('useTurnServices readCodeInputs', () => { }, ); + it("keeps the model main chat is compared with out of any other pane's turns", () => { + /** A comparison agent that has not loaded: main chat waits for it, a side pane does not. */ + const comparison = conversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_compare' }); + settings = { ...settings, addedConversation: comparison }; + const submitted = conversation({ endpoint: EModelEndpoint.openAI, model: 'gpt-5' }); + + const main = renderHook(() => useTurnServices({ index: 0, conversation: submitted }), { + wrapper, + }); + expect(main.result.current.canSubmit?.(submitted)).toBe(false); + expect(mockComparisons).toEqual({ workspace: comparison, approval: comparison }); + + const side = renderHook(() => useTurnServices({ index: 3, conversation: submitted }), { + wrapper, + }); + expect(side.result.current.canSubmit?.(submitted)).toBe(true); + expect(mockComparisons).toEqual({ workspace: null, approval: null }); + }); + it('checks the submitted target against current query data, not the rendered conversation', () => { const rendered = conversation({ endpoint: EModelEndpoint.openAI, model: 'gpt-5' }); const submitted = conversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_primary' }); diff --git a/client/src/hooks/Chat/contract.ts b/client/src/hooks/Chat/contract.ts index 35486df2b6..26b17dcf96 100644 --- a/client/src/hooks/Chat/contract.ts +++ b/client/src/hooks/Chat/contract.ts @@ -72,6 +72,8 @@ export type ChatConfig = { loaded?: boolean; /** Whether the deployment tracks token balances, refreshed after each turn. */ balanceEnabled?: boolean; + /** Whether a conversation may open beside the main one; off until the deployment has answered. */ + sideChat?: boolean; }; /** The signed-in account, as far as the chat reads it. */ diff --git a/client/src/hooks/Chat/services.ts b/client/src/hooks/Chat/services.ts index 46d26b8229..742b580d7f 100644 --- a/client/src/hooks/Chat/services.ts +++ b/client/src/hooks/Chat/services.ts @@ -35,7 +35,14 @@ export default function useTurnServices({ const discardFiles = useDiscardPastedFiles(index, conversation?.conversationId); const setFilesToDelete = useSetFilesToDelete(); const agentsMap = useAgentsMapContext(); - const { isTemporary, config, auth, getEphemeralAgent, addedConversation } = useChatSettings(); + const settings = useChatSettings(); + const { isTemporary, config, auth, getEphemeralAgent } = settings; + /** + * The conversation main chat is being compared with rides along with main chat's turns, from + * either of its panes. A conversation in any other pane is on its own: that comparison's + * readiness, workspace and approvals have no say in what it can send. + */ + const addedConversation = index === 0 || index === 1 ? settings.addedConversation : null; const { getExpiry } = useUserKey(conversation?.endpoint ?? ''); const getConversation = useGetConversation(index); const codeWorkspaceState = useCodeWorkspace(conversation, addedConversation); diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 6fb6751571..ac37f79656 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -2740,6 +2740,9 @@ "com_ui_permissions_updated_success": "Permissions updated successfully", "com_ui_schedules_filter": "Filter schedules...", "com_ui_sharing": "Sharing", + "com_ui_side_chat_load_error": "This conversation couldn't be loaded.", + "com_ui_side_chat_open_main": "Open as the main chat", + "com_ui_side_chat_panel": "Side chat", "com_ui_skill_content_error": "Couldn't load this skill's instructions.", "com_ui_skills_toggle_files": "Toggle files for {{0}}", "com_ui_view_agent_insights": "View insights", diff --git a/client/src/routes/ChatSettings.tsx b/client/src/routes/ChatSettings.tsx index 9553e7a702..9ac753390c 100644 --- a/client/src/routes/ChatSettings.tsx +++ b/client/src/routes/ChatSettings.tsx @@ -70,6 +70,7 @@ export default function ChatSettingsProvider({ children }: { children: ReactNode steerArmConfirmationTimeoutMs: ui?.steerArmConfirmationTimeoutMs, loaded: startupConfigLoaded, balanceEnabled: startupConfig?.balance?.enabled ?? false, + sideChat: startupConfig != null && ui?.sideChat !== false, }; }, [startupConfig, startupConfigLoaded]); const auth = useMemo( diff --git a/client/src/routes/__tests__/ChatSettings.spec.tsx b/client/src/routes/__tests__/ChatSettings.spec.tsx index 03302fdf11..07021f22ea 100644 --- a/client/src/routes/__tests__/ChatSettings.spec.tsx +++ b/client/src/routes/__tests__/ChatSettings.spec.tsx @@ -99,6 +99,7 @@ describe('ChatSettingsProvider', () => { canRenameRunningChat: false, loaded: false, balanceEnabled: false, + sideChat: false, }); }); @@ -129,6 +130,7 @@ describe('ChatSettingsProvider', () => { steerArmConfirmationTimeoutMs: 3_000, loaded: true, balanceEnabled: true, + sideChat: true, }); }); diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index 2debe01aab..edc45d42f0 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -6,6 +6,7 @@ import type { AgentDetail } from './agents.helpers'; import { MOCK_ENDPOINTS, getAccessToken, + MOCK_REPLY_TEXT, messagesView, requestJson, sendMessage, @@ -338,6 +339,113 @@ test.describe('detached subagent activity', () => { } } }); + + test('continues a finished child as a chat beside the conversation, and answers in it @scenario:subagent-continue-opens-side-chat', async ({ + page, + }) => { + test.setTimeout(120_000); + const label = `beside-${Date.now().toString(36)}`; + /** The fixture's parent dispatches exactly two children; the first is the one continued. */ + const childNames = [ + uniqueAgentName('E2E Side Chat Child A'), + uniqueAgentName('E2E Side Chat Child B'), + ]; + const parentName = uniqueAgentName('E2E Side Chat Parent'); + const createdAgentIds: string[] = []; + /** Every generation the page starts, by the conversation it is posted for. */ + const starts: Array = []; + page.on('request', (request) => { + const url = new URL(request.url()); + if (request.method() === 'POST' && /\/api\/agents\/chat\/[^/]+$/.test(url.pathname)) { + const body = request.postDataJSON() as { conversationId?: string | null } | null; + if (!url.pathname.endsWith('/abort')) { + starts.push(body?.conversationId ?? null); + } + } + }); + + try { + await page.goto('/c/new'); + const token = await getAccessToken(page); + const children: AgentDetail[] = []; + for (const childName of childNames) { + const child = await createAgent(page, token, childName); + children.push(child); + createdAgentIds.push(child.id); + } + const parent = await createAgent(page, token, parentName, { + enabled: true, + allowSelf: false, + agent_ids: children.map((child) => child.id), + }); + createdAgentIds.push(parent.id); + + await selectAgent(page, parentName); + const response = await sendMessageAndWaitForCompletion( + page, + `${DETACHED_ACTIVITY_MARKER}${children.map((child) => child.id).join(',')}:${label}`, + ); + expect(response.ok()).toBeTruthy(); + /** The path, not the whole address: the app drops the agent query once the turn is in. */ + const parentPath = new URL(page.url()).pathname; + + await page.getByRole('button', { name: 'Ran 2 agents' }).click(); + const cards = page.locator('[data-subagent-tool-call^="call_e2e_subagent_activity_"]'); + await expect(cards).toHaveCount(2, { timeout: 30_000 }); + await cards.first().click(); + const panel = childActivityPanel(page); + await expect(panel).toContainText(`E2E detached child 1 complete ${label}`, { + timeout: 30_000, + }); + + /** A finished child takes no more guidance: what the reader writes continues it as a + * chat of their own, which opens where the child's activity was. */ + const startsBefore = starts.length; + await panel.getByRole('textbox', { name: 'Message input' }).fill('What did you find?'); + await panel.getByRole('button', { name: 'Continue in a new chat' }).click(); + + const sideChat = page.getByRole('region', { name: 'Side chat' }); + await expect(sideChat).toBeVisible({ timeout: 30_000 }); + await expect(panel).toHaveCount(0); + /** The reader has not left the conversation the child ran under. */ + expect(new URL(page.url()).pathname).toBe(parentPath); + const sideConversationId = (await sideChat.getAttribute('data-side-chat')) ?? ''; + expect(sideConversationId).not.toBe(''); + expect(parentPath).not.toContain(sideConversationId); + + /** The child's history came with it, the reader's words are its next turn, and the + * reply streams into the same list. */ + await expect(sideChat).toContainText(`E2E detached child 1 complete ${label}`); + await expect(sideChat).toContainText('What did you find?'); + await expect(sideChat).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); + expect(starts.slice(startsBefore)).toEqual([sideConversationId]); + + /** A second turn from the side chat's own composer, once the first has settled. */ + const composer = sideChat.getByRole('textbox', { name: 'Message input' }); + await composer.fill('And then?'); + await expect(sideChat.getByRole('button', { name: 'Send message' })).toBeEnabled({ + timeout: 30_000, + }); + await composer.press('Enter'); + await expect(sideChat).toContainText('And then?'); + await expect + .poll(() => starts.slice(startsBefore)) + .toEqual([sideConversationId, sideConversationId]); + await expect(sideChat.getByText(MOCK_REPLY_TEXT)).toHaveCount(2, { timeout: 30_000 }); + + /** The same conversation as the page's main one, with both turns stored. */ + await sideChat.getByRole('button', { name: 'Open as the main chat' }).click(); + await expect(page).toHaveURL(new RegExp(`/c/${sideConversationId}$`)); + await expect(sideChat).toHaveCount(0); + const main = page.getByRole('main'); + await expect(main).toContainText('What did you find?'); + await expect(main).toContainText('And then?'); + } finally { + for (const agentId of createdAgentIds.reverse()) { + await cleanupAgent(page, agentId); + } + } + }); }); /** A subagent card's row is a picture of the child's thread, not part of this one: its folds diff --git a/librechat.example.yaml b/librechat.example.yaml index 9af7facab9..dcc50131b8 100644 --- a/librechat.example.yaml +++ b/librechat.example.yaml @@ -309,6 +309,9 @@ interface: # Allow the artifacts pane to be moved into its own browser window # (desktop only; the mobile sheet is unaffected). Default: true. artifactUndocking: true + # Continue a subagent's thread as a chat in the side panel, beside the conversation, + # instead of navigating to the new chat. Default: true. + sideChat: true # Ask each viewer before loading Google Tag Manager (ANALYTICS_GTM_ID). # Set false when the deployment settles consent itself, e.g. internal use. Default: true. # analyticsConsent: true diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index bf0caa778b..1b902702e9 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -307,6 +307,7 @@ export { export { default as SubagentConversation } from './components/subagents/conversation'; export { default as SharedSubagentActivityDialog } from './components/subagents/shared'; export { loadSubagentThreadPanel } from './components/subagents/load'; +export { loadSideChatPanel } from './components/side/load'; /** Part helpers moved from the app: copy and action buttons, language icons, expand/collapse. */ export { diff --git a/packages/chat/src/components/pane/Driven.tsx b/packages/chat/src/components/pane/Driven.tsx new file mode 100644 index 0000000000..4aebd7fa6e --- /dev/null +++ b/packages/chat/src/components/pane/Driven.tsx @@ -0,0 +1,37 @@ +import type { ReactElement } from 'react'; +import type { ChatScreenMessagesSlots } from './messages'; +import type { FollowedChat } from '../../react/follow'; +import { useDrivenContract } from '../../react/chat/driven'; +import { ContractThread } from './Followed'; + +export type DrivenThreadProps = { + /** The conversation driven. */ + id: string; + followed: FollowedChat; + /** The pane the host keys this chat's state by; see `useDrivenContract`. */ + index: number; + slots?: ChatScreenMessagesSlots; + /** Drawn under the list, inside the chat's contract: the surface's composer. */ + children?: (contract: ReturnType) => ReactElement | null; +}; + +/** + * A conversation the reader drives beside the main one: main chat's message list over a core + * `Chat`, with the contract that sends, reruns, continues and stops through it. Whatever takes + * the reader's words is drawn by the surface, which is handed that contract. + */ +export default function DrivenThread({ + id, + followed, + index, + slots, + children, +}: DrivenThreadProps): ReactElement { + const contract = useDrivenContract({ id, followed, index }); + return ( + <> + + {children?.(contract)} + + ); +} diff --git a/packages/chat/src/components/pane/Followed.tsx b/packages/chat/src/components/pane/Followed.tsx index ee60ee55f7..a8037b6fee 100644 --- a/packages/chat/src/components/pane/Followed.tsx +++ b/packages/chat/src/components/pane/Followed.tsx @@ -4,6 +4,7 @@ import type { TConversation } from 'librechat-data-provider'; import type { ReactElement } from 'react'; import type { TMessageAuthor } from '../../react/messages/author'; import type { MessagesHost } from '../../react/messages/host'; +import type { ChatContract } from '../../react/chat/contract'; import type { ChatScreenMessagesSlots } from './messages'; import type { FollowedChat } from '../../react/follow'; import { useMessagesHost, inertSeenSource, MessagesHostProvider } from '../../react/messages/host'; @@ -30,8 +31,9 @@ export type FollowedThreadProps = { const none = (): null => null; /** - * A followed conversation has no turn of the reader's waiting on it and no steers of theirs, and - * a surface narrow enough to sit beside a chat has no room for the navigation rail. + * A conversation beside the main one has no queued turn of the reader's waiting on it and no + * steers of theirs, and a surface narrow enough to sit beside a chat has no room for the + * navigation rail. */ const followedSlots: ChatScreenMessagesSlots = { renderPendingTurn: none, @@ -39,15 +41,17 @@ const followedSlots: ChatScreenMessagesSlots = { renderNav: none, }; -/** The followed chat's own list, where the page's host would hand a row main chat's. */ +/** The chat's own list, where the page's host would hand a row main chat's. */ const useFollowedMessages: MessagesHost['useGetMessages'] = () => useChatContext().getMessages; const useNoPendingTurn: MessagesHost['useHasPendingTurn'] = () => false; const useNoSeenSource: MessagesHost['useSeenSource'] = () => inertSeenSource; +const noAddedConversation = (): null => null; +const useNoAddedConversation: MessagesHost['useGetAddedConvo'] = () => noAddedConversation; /** - * The page's messages host with the members that act on main chat pointed at the followed one: - * a row reads the followed list, the reader has no queued turn here, and reading it marks no - * conversation of theirs seen. + * The page's messages host with the members that act on main chat pointed at this one: a row + * reads this chat's list, the reader has no queued turn here, reading it marks no conversation + * of theirs seen, and a rerun here does not take the model main chat is being compared with. */ function useFollowedMessagesHost(): MessagesHost { const host = useMessagesHost(); @@ -57,30 +61,32 @@ function useFollowedMessagesHost(): MessagesHost { useGetMessages: useFollowedMessages, useHasPendingTurn: useNoPendingTurn, useSeenSource: useNoSeenSource, + useGetAddedConvo: useNoAddedConversation, }), [host], ); } /** - * A followed conversation drawn by main chat's own message list: the same thread, rows, parts - * and scrolling, reading a chat contract built from the followed `Chat`. The hosts those rows - * read come from the tree it is mounted in, except the three that would act on main chat. It is - * never the page's main list, so it leaves the page-wide end marker and screenshot target to - * that one. + * A conversation that is not the page's main one, drawn by main chat's own message list: the + * same thread, rows, parts and scrolling, reading the chat contract it is given. The hosts those + * rows read come from the tree it is mounted in, except the three that would act on main chat. + * It leaves the page-wide end marker and screenshot target to the main list. */ -export default function FollowedThread({ - id, +export function ContractThread({ + contract, followed, - index, - conversation, slots, userAuthor, -}: FollowedThreadProps): ReactElement { - const contract = useFollowedContract({ id, followed, index, conversation }); - const { messages } = followed; +}: { + contract: ChatContract; + /** The conversation as read so far: its rows, and whether older ones are still to be read. */ + followed: FollowedChat; + slots?: ChatScreenMessagesSlots; + userAuthor?: TMessageAuthor; +}): ReactElement { + const { messages, hasEarlier, isLoadingEarlier, isEarlierError, loadEarlier } = followed; const messagesTree = useMemo(() => buildTree({ messages }), [messages]); - const { hasEarlier, isLoadingEarlier, isEarlierError, loadEarlier } = followed; /** The rows are the package's own, under whatever of the conversation is still to be read. */ const listSlots = useMemo( () => ({ @@ -113,3 +119,18 @@ export default function FollowedThread({ ); } + +/** A conversation the reader follows and does not drive, over a contract that takes no turns. */ +export default function FollowedThread({ + id, + followed, + index, + conversation, + slots, + userAuthor, +}: FollowedThreadProps): ReactElement { + const contract = useFollowedContract({ id, followed, index, conversation }); + return ( + + ); +} diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx new file mode 100644 index 0000000000..6db552c192 --- /dev/null +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -0,0 +1,427 @@ +/** + * @jest-environment jsdom + */ +import { atom, useAtom, Provider, createStore } from 'jotai'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { Constants, ContentTypes, EModelEndpoint } from 'librechat-data-provider'; +import type { TMessage, ChatEvent, TConversation } from 'librechat-data-provider'; +import type { ChatStream, ChatTransport, ChatSendRequest } from '../../../core'; +import type { SideChatHost } from '../../../react/side/host'; +import type { SideChat } from '../../../react/side/state'; +import type { ChatHost } from '../../../react/chat/host'; +import { MessagesHostProvider, useMessagesHost } from '../../../react/messages/host'; +import { createTurnServices } from '../../../react/chat/__fixtures__/services'; +import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; +import { ChatSurfaceProvider } from '../../../react/subagents/provider'; +import { createMessagesHost } from '../../../__fixtures__/messagesHost'; +import { SideChatHostProvider } from '../../../react/side/host'; +import { MessagePartsHostProvider } from '../../../react/host'; +import { ChatHostProvider } from '../../../react/chat/host'; +import { initEnglish } from '../../../__fixtures__/i18n'; +import { useFollowChat } from '../../../react/follow'; +import SideChatPanel from '../panel'; + +beforeAll(initEnglish); + +const conversationId = 'side-conversation'; + +const conversation: TConversation = { + conversationId, + endpoint: EModelEndpoint.agents, + agent_id: 'agent-1', + title: 'Release follow-up', + createdAt: '2026-11-18T00:00:00.000Z', + updatedAt: '2026-11-18T00:00:00.000Z', +}; + +const user: TMessage = { + messageId: 'user-1', + parentMessageId: Constants.NO_PARENT as string, + conversationId, + text: 'Investigate the release.', + sender: 'User', + isCreatedByUser: true, +}; + +const reply = (messageId: string, text: string, parentMessageId = 'user-1'): TMessage => ({ + messageId, + parentMessageId, + conversationId, + text, + sender: 'Assistant', + isCreatedByUser: false, + content: [{ type: ContentTypes.TEXT, text }], +}); + +type TestStream = ChatStream & { push(event: ChatEvent): void; closed: boolean }; + +const createStream = (): TestStream => { + const queued: ChatEvent[] = []; + let wake: (() => void) | undefined; + const stream: TestStream = { + streamId: conversationId, + generationCreatedAt: 3000, + closed: false, + push(event) { + queued.push(event); + wake?.(); + }, + close() { + stream.closed = true; + wake?.(); + }, + async *[Symbol.asyncIterator]() { + while (true) { + while (queued.length > 0) { + yield queued.shift() as ChatEvent; + } + if (stream.closed) { + return; + } + await new Promise((resolve) => { + wake = resolve; + }); + } + }, + }; + return stream; +}; + +const final = (requestMessage: TMessage, responseMessage: TMessage): ChatEvent => + ({ + type: 'final', + data: { final: true, conversation: { conversationId }, requestMessage, responseMessage }, + }) as ChatEvent; + +/** The model main chat is being compared with, which the page's host would hand a row. */ +const comparison = { conversationId: 'main-comparison', endpoint: 'openAI' } as TConversation; + +/** Reads what a row of the side chat is given, from where a row reads it. */ +function UserRow({ text }: { text: string }) { + const added = useMessagesHost().useGetAddedConvo()(); + return
{`user=${text}`}
; +} + +const messagesHost = createMessagesHost({ + useGetAddedConvo: () => () => comparison, + renderMessageBody: ({ message }) => , +}); +const partsHost = createMessagePartsHost({ + renderContentParts: ({ content }) => ( +
+ {`reply=${(content ?? []).map((part) => (part as { text?: string } | undefined)?.text ?? '').join('')}`} +
+ ), +}); + +function setup({ + chat = { conversation }, + stored = [user, reply('response-1', 'It shipped.')], + loadMessages = jest.fn(async () => stored), +}: { + chat?: SideChat; + stored?: TMessage[]; + loadMessages?: jest.Mock>; +} = {}) { + const streams: TestStream[] = []; + const sendMessages = jest.fn( + async (_request: ChatSendRequest): ReturnType => { + const stream = createStream(); + streams.push(stream); + return { status: 'stream', stream }; + }, + ); + const abort = jest.fn(async () => ({ success: true })); + const transport: ChatTransport = { + sendMessages, + abort, + reconnectToStream: async () => null, + getStatus: async () => ({ active: false }), + }; + const openConversation = jest.fn(); + const sideChatHost: SideChatHost = { + useChat: ({ conversationId: id, endpoint }, options) => + useFollowChat({ id: id ?? '', transport, loadMessages, endpoint, ...options }), + useOpenConversation: () => openConversation, + useSheetLayout: () => false, + useClearsFooter: () => false, + }; + /** One pane store for everything that reads the pane, as the app's is. */ + const paneAtom = atom(null); + const chatHost: ChatHost = { + usePaneConversation: () => { + const [held, setConversation] = useAtom(paneAtom); + return { conversation: held, setConversation }; + }, + useNewConversation: () => () => undefined, + useTurnServices: () => createTurnServices(), + useAbortStream: () => () => Promise.reject(new Error('unused')), + useMessageCache: () => { + throw new Error('A side chat reads its own messages'); + }, + useFeedbackEnabled: () => false, + useMessages: () => ({ messages: null, isLoading: false, isFetching: false }), + }; + const onClose = jest.fn(); + const onHandedTextTaken = jest.fn(); + const handOffComposerText = jest.fn(); + const queryClient = new QueryClient(); + const store = createStore(); + const tree = (current: SideChat) => ( + + + (), + }, + claimForeground: () => undefined, + handOffComposerText, + }} + > + + + + + onHandedTextTaken()} + /> + + + + + + + + ); + const view = render(tree(chat)); + return { + ...view, + rerenderWith: (next: SideChat) => view.rerender(tree(next)), + /** Draws the panel again from nothing, as the layout does when it moves it. */ + remount: () => { + view.unmount(); + return render(tree(chat)); + }, + streams, + sendMessages, + abort, + openConversation, + onClose, + onHandedTextTaken, + handOffComposerText, + loadMessages, + }; +} + +const rows = () => screen.queryAllByTestId('row').map((row) => row.textContent); +const field = () => screen.getByRole('textbox', { name: 'Message input' }); +const settle = () => + act(async () => { + await new Promise((resolve) => setTimeout(resolve, 40)); + }); + +describe('SideChatPanel', () => { + it('shows the conversation beside the main one, under its title', async () => { + setup(); + + expect(screen.getByRole('status')).toHaveTextContent('Loading'); + await waitFor(() => + expect(rows()).toEqual(['user=Investigate the release.', 'reply=It shipped.']), + ); + expect(screen.getByRole('region', { name: 'Side chat' })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Release follow-up' })).toBeInTheDocument(); + expect(field()).toHaveAttribute('placeholder', 'Message Release follow-up'); + }); + + it('sends what the reader types as the conversation’s next turn, and stops it', async () => { + const { sendMessages, streams, abort } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + const send = screen.getByTestId('composer-send-button'); + expect(send).toBeDisabled(); + + fireEvent.change(field(), { target: { value: 'What changed?' } }); + await waitFor(() => expect(send).toBeEnabled()); + fireEvent.click(send); + + await waitFor(() => expect(streams).toHaveLength(1)); + expect(sendMessages.mock.calls[0][0]).toMatchObject({ + trigger: 'submit-message', + payload: { + endpoint: EModelEndpoint.agents, + conversationId, + text: 'What changed?', + parentMessageId: 'response-1', + }, + }); + expect(field()).toHaveValue(''); + expect(rows().slice(2)).toEqual(['user=What changed?', 'reply=']); + + /** With nothing typed while it runs, the send control is main chat's Stop. */ + fireEvent.click(await screen.findByRole('button', { name: 'Stop generating' })); + await waitFor(() => expect(abort).toHaveBeenCalledTimes(1)); + expect(abort.mock.calls[0]).toMatchObject([ + { endpoint: EModelEndpoint.agents, streamId: conversationId, generationCreatedAt: 3000 }, + ]); + }); + + it('settles the reply and takes the next message', async () => { + const { streams, sendMessages } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'What changed?' } }); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(streams).toHaveLength(1)); + const asked: TMessage = { + ...user, + messageId: sendMessages.mock.calls[0][0].payload.messageId as string, + parentMessageId: 'response-1', + text: 'What changed?', + }; + + act(() => { + streams[0].push({ + type: 'created', + data: { created: true, message: asked, turn: { responseMessageId: 'response-2' } }, + } as ChatEvent); + streams[0].push(final(asked, reply('response-2', 'Two fixes.', asked.messageId))); + }); + await waitFor(() => + expect(rows().slice(2)).toEqual(['user=What changed?', 'reply=Two fixes.']), + ); + await settle(); + + expect(screen.queryByRole('button', { name: 'Stop generating' })).not.toBeInTheDocument(); + fireEvent.change(field(), { target: { value: 'Which ones?' } }); + await waitFor(() => expect(screen.getByTestId('composer-send-button')).toBeEnabled()); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(streams).toHaveLength(2)); + expect(sendMessages.mock.calls[1][0].payload).toMatchObject({ + text: 'Which ones?', + parentMessageId: 'response-2', + }); + }); + + it('sends the words handed over with the conversation once, as its next turn', async () => { + const { sendMessages, streams, onHandedTextTaken, rerenderWith } = setup({ + chat: { conversation, text: 'Carry on from here.' }, + }); + + await waitFor(() => expect(streams).toHaveLength(1)); + expect(sendMessages.mock.calls[0][0].payload).toMatchObject({ + text: 'Carry on from here.', + parentMessageId: 'response-1', + }); + expect(onHandedTextTaken).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + + /** The owner has not dropped the words yet; they are not a second turn. */ + rerenderWith({ conversation, text: 'Carry on from here.' }); + await settle(); + expect(sendMessages).toHaveBeenCalledTimes(1); + expect(onHandedTextTaken).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + }); + + it('says when the conversation could not be loaded, and tries again', async () => { + const loadMessages = jest + .fn, []>() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue([user, reply('response-1', 'It shipped.')]); + setup({ loadMessages }); + + expect(await screen.findByRole('alert')).toHaveTextContent( + "This conversation couldn't be loaded.", + ); + expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Retry' })); + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(field()).toBeInTheDocument(); + }); + + it('moves the conversation into the main chat’s place, or closes', async () => { + const { openConversation, onClose } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + expect(openConversation).toHaveBeenCalledWith(expect.objectContaining({ conversationId })); + expect(onClose).toHaveBeenCalledTimes(1); + + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + expect(onClose).toHaveBeenCalledTimes(2); + }); + + it('takes the unsent words along when the conversation moves to the main chat', async () => { + const { openConversation, handOffComposerText } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'Not sent yet' } }); + + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + + expect(handOffComposerText).toHaveBeenCalledWith(conversationId, 'Not sent yet'); + expect(openConversation).toHaveBeenCalledTimes(1); + }); + + it('hands nothing along when nothing was written', async () => { + const { handOffComposerText } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + + expect(handOffComposerText).not.toHaveBeenCalled(); + }); + + it('puts the words of a turn the server never kept back in the field', async () => { + const { streams } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'What changed?' } }); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(streams).toHaveLength(1)); + expect(field()).toHaveValue(''); + + /** Stopped before the server had saved the turn. */ + act(() => + streams[0].push({ + type: 'final', + data: { + final: true, + earlyAbort: true, + conversation: { conversationId }, + requestMessage: null, + responseMessage: null, + }, + } as unknown as ChatEvent), + ); + + await waitFor(() => expect(field()).toHaveValue('What changed?')); + expect(rows()).toEqual(['user=Investigate the release.', 'reply=It shipped.']); + }); + + it('keeps a rerun in the side chat to its own conversation', async () => { + setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + + /** Not the model main chat is being compared with, which a rerun would otherwise send to. */ + expect(screen.getAllByTestId('row')[0]).toHaveAttribute('data-added', 'none'); + }); + + it('keeps the unsent words when the layout draws the panel again', async () => { + const { remount } = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'Half a thought' } }); + + /** Crossing the breakpoint moves the panel between a column and a sheet: a new mount. */ + remount(); + + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(field()).toHaveValue('Half a thought'); + }); +}); diff --git a/packages/chat/src/components/side/load.ts b/packages/chat/src/components/side/load.ts new file mode 100644 index 0000000000..9987ccbc4e --- /dev/null +++ b/packages/chat/src/components/side/load.ts @@ -0,0 +1,8 @@ +/** + * The side chat opens on demand, so it loads through a dynamic import: exporting it statically + * would put its code in the components entry, which every page loads. The app wraps this in + * its own lazy boundary. + */ +export function loadSideChatPanel(): Promise { + return import('./panel'); +} diff --git a/packages/chat/src/components/side/panel.tsx b/packages/chat/src/components/side/panel.tsx new file mode 100644 index 0000000000..a7c4bdbab1 --- /dev/null +++ b/packages/chat/src/components/side/panel.tsx @@ -0,0 +1,293 @@ +import { useRef, useEffect, useCallback } from 'react'; +import { useAtom } from 'jotai'; +import { ArrowUpRight, X } from 'lucide-react'; +import { cn, Button, Composer, useLocalize, useFocusTrap } from '@librechat/client'; +import type { ComposerStopProps, ComposerKeyVerdict } from '@librechat/client'; +import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'; +import type { ChatContract } from '../../react/chat/contract'; +import type { SideChat } from '../../react/side/state'; +import type { SubmittedTurn } from '../../core'; +import { SIDE_CHAT_PANE, sideChatDraftFamily } from '../../react/side/state'; +import { useChatSurface } from '../../react/subagents/surface'; +import { resolveComposerKeyDown } from '../../core/shortcuts'; +import { useSideChatHost } from '../../react/side/host'; +import { useChatHost } from '../../react/chat/host'; +import DrivenThread from '../pane/Driven'; + +type SideChatComposerProps = { + contract: ChatContract; + /** The reader's unsent words, which the panel holds so they outlive the composer. */ + value: string; + onChange: (value: string) => void; + conversationId: string; + title: string; + /** Whether the conversation is in and the pane holds it, so a turn can be built for it. */ + ready: boolean; + /** Words written for this conversation before it opened; see {@link SideChat.text}. */ + handedText?: string; + onHandedTextTaken: () => void; + clearsFooter: boolean; +}; + +/** + * The side chat's composer: main chat's field at panel scale. Sending is the contract's `ask`, + * and with nothing typed while a generation runs the send control is main chat's Stop. + */ +function SideChatComposer({ + contract, + value, + onChange: setValue, + conversationId, + title, + ready, + handedText, + onHandedTextTaken, + clearsFooter, +}: SideChatComposerProps): ReactNode { + const localize = useLocalize(); + const { + enterToSend, + composerBindings: { shortcutsEnabled, submitOverride, yieldedChords }, + } = useChatSurface(); + const { ask, isSubmitting, stopGenerating } = contract; + + /** + * Words the reader wrote before this conversation opened are its next turn. They are sent + * once, when the conversation can take them; if it cannot, they are left in the field. + */ + const handed = useRef(); + useEffect(() => { + if (!ready || handedText == null || handedText === '' || handed.current === conversationId) { + return; + } + handed.current = conversationId; + if (ask({ text: handedText }) === false) { + setValue(handedText); + } + onHandedTextTaken(); + }, [ask, conversationId, handedText, onHandedTextTaken, ready, setValue]); + + const submit = useCallback(() => { + const text = value.trim(); + if (text === '' || ask({ text }) === false) { + return; + } + setValue(''); + }, [ask, setValue, value]); + + /** The main chat form's own Enter decision table, so a rebound submit shortcut holds here. */ + const resolveKeyVerdict = useCallback( + (event: ReactKeyboardEvent, isComposing: boolean): ComposerKeyVerdict => { + const action = resolveComposerKeyDown(event, { + isComposing, + isSubmitting: false, + allowSubmitWhileGenerating: false, + hasDuringRunModifier: false, + shortcutsEnabled, + enterToSend, + submitOverride, + yieldedChords, + }); + if (action === 'submit' || action === 'newline' || action === 'block') { + return action; + } + return 'none'; + }, + [enterToSend, shortcutsEnabled, submitOverride, yieldedChords], + ); + + const stopProps: ComposerStopProps = isSubmitting + ? { onStop: () => void stopGenerating(), stopLabel: localize('com_nav_stop_generating') } + : {}; + + return ( +
+ +
+ ); +} + +/** + * A conversation of the reader's own, open beside the main one: main chat's message list and a + * composer, driven through a core `Chat`. The main conversation stays where it is; the control + * in the header moves this one into its place. + */ +export default function SideChatPanel({ + chat, + onClose, + onHandedTextTaken, +}: { + chat: SideChat; + onClose: () => void; + /** The words handed over with the conversation were sent, or put in the field. */ + onHandedTextTaken: () => void; +}): ReactNode { + const localize = useLocalize(); + const host = useSideChatHost(); + const isSheet = host.useSheetLayout(); + const clearsFooter = host.useClearsFooter(); + const openConversation = host.useOpenConversation(); + const { handOffComposerText } = useChatSurface(); + const conversationId = chat.conversation.conversationId ?? ''; + const [draft, setDraft] = useAtom(sideChatDraftFamily(conversationId)); + /** + * A turn stopped before the server kept it is gone from the list. Its words go back in the + * field, as main chat keeps them as a draft, unless the reader has written something since. + */ + const takeBack = useCallback( + (turn: SubmittedTurn) => { + const { submission } = turn; + if (submission.isRegenerate === true) { + return; + } + setDraft((current) => (current === '' ? (submission.userMessage.text ?? '') : current)); + }, + [setDraft], + ); + const followed = host.useChat(chat.conversation, { onWithdrawn: takeBack }); + const panelRef = useRef(null); + + /** The pane's conversation is what a turn is built from, so the pane is told which it holds. */ + const pane = useChatHost().usePaneConversation(SIDE_CHAT_PANE); + const { setConversation } = pane; + const opened = chat.conversation; + useEffect(() => { + setConversation(opened); + return () => setConversation(null); + }, [opened, setConversation]); + const held = pane.conversation?.conversationId === conversationId; + + useFocusTrap(panelRef, isSheet); + useEffect(() => { + if (!isSheet) { + return; + } + const handleKeyDown = (event: KeyboardEvent) => { + const panel = panelRef.current; + if (event.key !== 'Escape' || event.defaultPrevented || panel == null) { + return; + } + if (event.target instanceof Node && panel.contains(event.target)) { + event.preventDefault(); + onClose(); + } + }; + document.addEventListener('keydown', handleKeyDown); + return () => document.removeEventListener('keydown', handleKeyDown); + }, [isSheet, onClose]); + + const title = pane.conversation?.title ?? opened.title ?? localize('com_ui_new_chat'); + const openAsMain = useCallback(() => { + /** Words not sent yet go with the conversation, to the composer it opens under. */ + if (draft.trim() !== '') { + handOffComposerText(conversationId, draft); + } + openConversation(pane.conversation ?? opened); + onClose(); + }, [ + conversationId, + draft, + handOffComposerText, + onClose, + openConversation, + opened, + pane.conversation, + ]); + + let body: ReactNode; + if (followed.isLoadError) { + body = ( +
+ {localize('com_ui_side_chat_load_error')} + +
+ ); + } else if (followed.isLoading && followed.messages.length === 0) { + body = ( +
+ {localize('com_ui_loading')} +
+ ); + } else { + body = ( + + {(contract) => ( + + )} + + ); + } + + return ( + + ); +} diff --git a/packages/chat/src/components/subagents/__tests__/panel.spec.tsx b/packages/chat/src/components/subagents/__tests__/panel.spec.tsx index b4345ccdf7..356bf23855 100644 --- a/packages/chat/src/components/subagents/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/subagents/__tests__/panel.spec.tsx @@ -54,6 +54,8 @@ const mockForkMutate = jest.fn(); const mockControlMutate = jest.fn(); const mockNavigateToConvo = jest.fn(); const mockNavigate = jest.fn(); +/** Set by a test whose app offers a place beside the conversation. */ +let mockOpenBeside: jest.Mock | undefined; const mockShowToast = jest.fn(); const mockGetSubagentThread = jest.fn(); const mockApprovalProviderMounted = jest.fn(); @@ -190,6 +192,7 @@ const subagentsHost: SubagentsHost = createSubagentsHost({ useNavigation: () => ({ openConversation: (conversation) => mockNavigateToConvo(conversation), openConversationId: (conversationId) => mockNavigate(conversationId), + ...(mockOpenBeside != null && { openBeside: mockOpenBeside }), }), /** The app scales the sheet breakpoint by the reader's text size before it asks. */ useSheetLayout: () => @@ -665,6 +668,7 @@ describe('SubagentThreadPanel', () => { mockViewportWidth = null; mockRemScale = 1; mockEnterToSend = true; + mockOpenBeside = undefined; mockClaimForeground.mockClear(); mockHandOffComposerText.mockClear(); mockApprovalProviderMounted.mockClear(); @@ -2853,6 +2857,56 @@ describe('SubagentThreadPanel', () => { ).toEqual([]); }); + it('opens the continued conversation beside this one where the app has a place for it', () => { + mockOpenBeside = jest.fn(); + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + render( + + + , + ); + + fireEvent.change(screen.getByLabelText('com_ui_message_input'), { + target: { value: 'Take this further.' }, + }); + fireEvent.keyDown(screen.getByLabelText('com_ui_message_input'), { key: 'Enter' }); + const mutationOptions = mockForkMutate.mock.calls[0][1]; + const conversation = { conversationId: 'continued-chat', agent_id: 'agent-1' }; + act(() => mutationOptions.onSuccess({ conversation, messages: [] })); + + /** The reader stays where they are: the words go with the conversation, as its next turn. */ + expect(mockOpenBeside).toHaveBeenCalledWith(conversation, 'Take this further.'); + expect(mockNavigateToConvo).not.toHaveBeenCalled(); + expect(mockHandOffComposerText).not.toHaveBeenCalled(); + }); + + it('opens the continued conversation beside this one with no words when none were written', () => { + mockOpenBeside = jest.fn(); + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + render( + + + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_continue_new_chat' })); + const mutationOptions = mockForkMutate.mock.calls[0][1]; + const conversation = { conversationId: 'continued-chat', agent_id: 'agent-1' }; + act(() => mutationOptions.onSuccess({ conversation, messages: [] })); + + expect(mockOpenBeside).toHaveBeenCalledWith(conversation, undefined); + }); + /** The composer is shared across selections, so a continuation that lands * after the reader has moved on must hand over the words IT was sent with, * and must not take the words now in front of them. */ diff --git a/packages/chat/src/components/subagents/panel.tsx b/packages/chat/src/components/subagents/panel.tsx index ef3d6c61bf..415e4ef454 100644 --- a/packages/chat/src/components/subagents/panel.tsx +++ b/packages/chat/src/components/subagents/panel.tsx @@ -435,6 +435,14 @@ export default function SubagentThreadPanel({ const draft = stillItsOwnComposer ? controlMessageRef.current.trim() : (continuation?.text ?? ''); + if (result.conversation != null && navigation.openBeside != null) { + /** The continuation takes this panel's place beside the conversation, and the words + * the reader sent to get here are its next turn. */ + if (stillItsOwnComposer) setControlMessage(''); + resetSelection(); + navigation.openBeside(result.conversation, draft === '' ? undefined : draft); + return; + } if (continuedConversationId != null && draft !== '') { handOffComposerText(continuedConversationId, draft); } diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index 5904f3acfa..df62bba6f5 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -132,6 +132,10 @@ export { useFollowedContract } from './react/chat/followed'; export type { FollowedContractOptions } from './react/chat/followed'; export { useDrivenContract } from './react/chat/driven'; export type { DrivenContractOptions } from './react/chat/driven'; +export { sideChatAtom, SIDE_CHAT_PANE } from './react/side/state'; +export type { SideChat } from './react/side/state'; +export { useSideChatHost, SideChatHostProvider } from './react/side/host'; +export type { SideChatHost } from './react/side/host'; export { useSnapshot } from './react/snapshot'; export { ReactQueryChatState } from './react/state'; export type { Subscribe, SnapshotOptions } from './react/snapshot'; diff --git a/packages/chat/src/react/side/host.tsx b/packages/chat/src/react/side/host.tsx new file mode 100644 index 0000000000..8e190cf349 --- /dev/null +++ b/packages/chat/src/react/side/host.tsx @@ -0,0 +1,46 @@ +import { useContext, createContext } from 'react'; +import type { TConversation } from 'librechat-data-provider'; +import type { Context, ReactNode } from 'react'; +import type { FollowedChat, FollowChatOptions } from '../follow'; + +/** + * What a side chat reads from the app. Members named `use*` are hooks, called unconditionally, + * and a host stays the same object for the life of the tree it wraps. + */ +export interface SideChatHost { + /** + * The conversation as a chat the reader drives: its stored messages, the generation running + * under it, and a transport that can start and stop one on the conversation's endpoint. + */ + useChat: ( + conversation: Pick, + options?: Pick, + ) => FollowedChat; + /** Opens the conversation as the page's main one. */ + useOpenConversation: () => (conversation: TConversation) => void; + /** Whether the panel is a modal sheet over the chat rather than a region beside it. */ + useSheetLayout: () => boolean; + /** Whether the deployment draws a footer bar the panel's composer has to clear. */ + useClearsFooter: () => boolean; +} + +const SideChatHostContext: Context = createContext(null); + +/** Supplies the host a side chat reads from. */ +export function SideChatHostProvider({ + host, + children, +}: { + host: SideChatHost; + children?: ReactNode; +}): ReactNode { + return {children}; +} + +export function useSideChatHost(): SideChatHost { + const host = useContext(SideChatHostContext); + if (host == null) { + throw new Error('A side chat needs a SideChatHostProvider above it.'); + } + return host; +} diff --git a/packages/chat/src/react/side/state.ts b/packages/chat/src/react/side/state.ts new file mode 100644 index 0000000000..a0b2e16655 --- /dev/null +++ b/packages/chat/src/react/side/state.ts @@ -0,0 +1,29 @@ +import { atom } from 'jotai'; +import { atomFamily } from 'jotai/utils'; +import type { TConversation } from 'librechat-data-provider'; +import type { PrimitiveAtom } from 'jotai'; + +/** + * The pane number a side chat keys its per-pane state by. Its own, so it shares none of that + * state with the main chat (`0`), the added pane (`1`) or a subagent's thread (`2`). + */ +export const SIDE_CHAT_PANE = 3; + +/** A conversation of the reader's own, open beside the main one. */ +export type SideChat = { + conversation: TConversation; + /** Words the reader had already written for it, sent as its next turn once it has loaded. */ + text?: string; +}; + +/** The side chat on screen, if any. One at a time: it takes the page's side panel. */ +export const sideChatAtom: PrimitiveAtom = atom(null); + +/** + * The words the reader has written for a side chat and not sent, by its conversation. Held + * outside the panel, which is drawn again when the layout moves it between a column and a + * sheet, and in memory only: an unsent draft is not written to storage. + */ +export const sideChatDraftFamily: (conversationId: string) => PrimitiveAtom = atomFamily( + (_conversationId: string) => atom(''), +); diff --git a/packages/chat/src/react/subagents/host.tsx b/packages/chat/src/react/subagents/host.tsx index 2a4a4492e0..5d167760a7 100644 --- a/packages/chat/src/react/subagents/host.tsx +++ b/packages/chat/src/react/subagents/host.tsx @@ -109,6 +109,11 @@ export type SubagentNavigation = { openConversation: (conversation: TConversation) => void; /** Opens a conversation by id. */ openConversationId: (conversationId: string) => void; + /** + * Opens a conversation beside the one on screen, with words the reader wrote for it as its + * next turn. Absent where the app has no place beside the conversation, or keeps it closed. + */ + openBeside?: (conversation: TConversation, text?: string) => void; }; /** diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index c72a692cb9..834d15d80b 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -3534,6 +3534,10 @@ export const interfaceSchema = z * default; a deployment that cannot use popups can turn it off and keep * the docked pane. */ artifactUndocking: z.boolean().optional(), + /** Opening a conversation of the reader's own beside the main one: continuing a + * subagent's thread opens the new chat in the side panel instead of leaving + * the conversation. Enabled by default; false restores the navigation. */ + sideChat: z.boolean().optional(), /** Asks each viewer for consent before Google Tag Manager (`ANALYTICS_GTM_ID`) * loads. A deployment that settles consent itself, such as an internal one * covered by its own policy, can set false to load the container without the @@ -3777,6 +3781,7 @@ export const interfaceSchema = z contextUsage: true, contextCost: false, artifactUndocking: true, + sideChat: true, feedback: true, peoplePicker: { users: true, diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts index c25f3c36a1..871662af4b 100644 --- a/packages/data-schemas/src/app/interface.spec.ts +++ b/packages/data-schemas/src/app/interface.spec.ts @@ -236,6 +236,24 @@ describe('loadDefaultInterface', () => { expect(interfaceConfig?.artifactUndocking).toBe(true); }); + it('carries a disabled side chat flag to the clients', async () => { + const interfaceConfig = await loadDefaultInterface({ + config: { interface: { sideChat: false } }, + configDefaults: getConfigDefaults(), + }); + + expect(interfaceConfig?.sideChat).toBe(false); + }); + + it('uses the schema default for side chats when not configured', async () => { + const interfaceConfig = await loadDefaultInterface({ + config: {}, + configDefaults: getConfigDefaults(), + }); + + expect(interfaceConfig?.sideChat).toBe(true); + }); + it('carries a disabled analytics consent prompt to the clients', async () => { const interfaceConfig = await loadDefaultInterface({ config: { interface: { analyticsConsent: false } }, diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts index 72f0ed3db8..3e74c44eea 100644 --- a/packages/data-schemas/src/app/interface.ts +++ b/packages/data-schemas/src/app/interface.ts @@ -101,6 +101,7 @@ export async function loadDefaultInterface({ mascot: interfaceConfig?.mascot ?? defaults.mascot, contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage, artifactUndocking: interfaceConfig?.artifactUndocking ?? defaults.artifactUndocking, + sideChat: interfaceConfig?.sideChat ?? defaults.sideChat, analyticsConsent: interfaceConfig?.analyticsConsent, contextCost: interfaceConfig?.contextCost ?? defaults.contextCost, feedback: interfaceConfig?.feedback ?? defaults.feedback,