From 32aedaad70efe4e13b053b85092de0e68549b1e4 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:16:37 -0800 Subject: [PATCH] fix: Wait for Side Chat Target Readiness (#18480) --- client/src/Providers/SideChatHostContext.tsx | 43 +++++++-- .../__tests__/SideChatHostContext.spec.tsx | 89 ++++++++++++++++++- e2e/specs/mock/subagent-activity.spec.ts | 5 ++ .../components/side/__tests__/panel.spec.tsx | 27 +++++- packages/chat/src/react/side/host.tsx | 2 +- 5 files changed, 156 insertions(+), 10 deletions(-) diff --git a/client/src/Providers/SideChatHostContext.tsx b/client/src/Providers/SideChatHostContext.tsx index 6edc5080c2..25d827298d 100644 --- a/client/src/Providers/SideChatHostContext.tsx +++ b/client/src/Providers/SideChatHostContext.tsx @@ -1,14 +1,20 @@ 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 { + dataService, + QueryKeys, + isAgentsEndpoint, + isEphemeralAgentId, +} from 'librechat-data-provider'; import type { FollowedChat, SideChatHost, FollowChatOptions } from '@librechat/chat/react'; -import type { TConversation } from 'librechat-data-provider'; +import type { Agent, 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 { retryTransientQuery } from '~/data-provider/retry'; import useScaledMaxWidth from '~/hooks/useScaledMaxWidth'; import { useChatTransport } from './ChatTransportContext'; import { useChatSettings } from './ChatSettingsContext'; @@ -19,11 +25,16 @@ import { fetchStreamStatus } from '~/data-provider'; * route, and its generations started, streamed and stopped over the transport main chat uses. */ function useChat( - { conversationId, endpoint }: Pick, + { + conversationId, + endpoint, + agent_id, + }: Pick, options?: Pick, ): FollowedChat { const id = conversationId ?? ''; const { token } = useChatSettings().auth; + const queryClient = useQueryClient(); const transport = useChatTransport(); const generation = useMemo( () => @@ -36,13 +47,35 @@ function useChat( }), [transport, token], ); - const loadMessages = useCallback(() => dataService.getMessagesByConvoId(id), [id]); + const loadMessages = useCallback(async () => { + const key = [QueryKeys.agent, agent_id]; + const cached = queryClient.getQueryState(key); + const needsTarget = + isAgentsEndpoint(endpoint) && + agent_id != null && + !isEphemeralAgentId(agent_id) && + !(cached?.status === 'success' && cached.data?.id === agent_id); + /** Warm the same authoritative query the submission guard reads, alongside history. */ + const target = needsTarget + ? queryClient.fetchQuery({ + queryKey: key, + queryFn: () => dataService.getAgentById({ agent_id }), + retry: retryTransientQuery, + }) + : Promise.resolve(); + const [messages] = await Promise.all([ + dataService.getMessagesByConvoId(id), + /** A denied target must not hide readable history; the send guard retains the draft. */ + target.catch(() => undefined), + ]); + return messages; + }, [agent_id, endpoint, id, queryClient]); /** * 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 onAttachment = useAttachmentHandler(queryClient); const beside = useMemo(() => ({ onAttachment }), [onAttachment]); return useFollowChat({ id, diff --git a/client/src/Providers/__tests__/SideChatHostContext.spec.tsx b/client/src/Providers/__tests__/SideChatHostContext.spec.tsx index 5e0cfff591..6ce0e1dc9d 100644 --- a/client/src/Providers/__tests__/SideChatHostContext.spec.tsx +++ b/client/src/Providers/__tests__/SideChatHostContext.spec.tsx @@ -14,6 +14,7 @@ import type { Transport } from '~/hooks/Chat/contract'; import { ChatTransportContext, defaultChatTransport } from '../ChatTransportContext'; const mockMessages = jest.fn(); +const mockAgent = jest.fn(); jest.mock('librechat-data-provider', () => { const actual = jest.requireActual('librechat-data-provider'); return { @@ -21,6 +22,7 @@ jest.mock('librechat-data-provider', () => { dataService: { ...actual.dataService, getMessagesByConvoId: (...args: unknown[]) => mockMessages(...args), + getAgentById: (...args: unknown[]) => mockAgent(...args), }, }; }); @@ -63,8 +65,10 @@ function createTransport() { return { transport, attachments, start, abort }; } -const setup = () => { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); +const setup = ( + target = conversation, + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }), +) => { const harness = createTransport(); const wrapper = ({ children }: { children: React.ReactNode }) => ( @@ -75,16 +79,95 @@ const setup = () => { ); - const view = renderHook(() => appSideChatHost.useChat(conversation), { wrapper }); + const view = renderHook(() => appSideChatHost.useChat(target), { wrapper }); return { ...view, ...harness, client }; }; describe("the app's side chat host", () => { beforeEach(() => { mockMessages.mockReset(); + mockAgent.mockReset(); mockStreamStatus.mockReset(); }); + it('waits for the authoritative saved-agent query alongside history before becoming ready', async () => { + let finish!: (agent: { id: string }) => void; + const target = { ...conversation, agent_id: 'agent_side_target' }; + mockStreamStatus.mockResolvedValue({ active: false }); + mockMessages.mockResolvedValue([asked]); + mockAgent.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const { result, client } = setup(target); + await waitFor(() => expect(mockMessages).toHaveBeenCalled()); + expect(result.current.isLoading).toBe(true); + await waitFor(() => expect(mockAgent).toHaveBeenCalledTimes(1)); + await act(async () => finish({ id: target.agent_id })); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + expect(result.current.messages).toEqual([asked]); + expect(client.getQueryData([QueryKeys.agent, target.agent_id])).toEqual({ + id: target.agent_id, + }); + act(() => result.current.retry()); + await waitFor(() => expect(mockMessages).toHaveBeenCalledTimes(2)); + expect(mockAgent).toHaveBeenCalledTimes(1); + }); + + it.each([403, 404])( + 'retains readable history when target metadata fails with %s', + async (status) => { + const target = { ...conversation, agent_id: 'agent_side_target' }; + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() }, + }); + mockStreamStatus.mockResolvedValue({ active: false }); + mockMessages.mockResolvedValue([asked]); + mockAgent.mockRejectedValue({ status }); + const { result } = setup(target, client); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + expect(result.current.isLoadError).toBe(false); + expect(result.current.messages).toEqual([asked]); + expect(client.getQueryState([QueryKeys.agent, target.agent_id])?.status).toBe('error'); + }, + ); + + it('reuses matching cached target metadata without another request', async () => { + const target = { ...conversation, agent_id: 'agent_side_target' }; + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData([QueryKeys.agent, target.agent_id], { id: target.agent_id }); + mockStreamStatus.mockResolvedValue({ active: false }); + mockMessages.mockResolvedValue([asked]); + const { result } = setup(target, client); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + expect(mockAgent).not.toHaveBeenCalled(); + }); + + it('shares an in-flight target read with existing agent consumers', async () => { + let finish!: (agent: { id: string }) => void; + const target = { ...conversation, agent_id: 'agent_side_target' }; + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + mockAgent.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const existing = client.fetchQuery([QueryKeys.agent, target.agent_id], () => mockAgent()); + mockStreamStatus.mockResolvedValue({ active: false }); + mockMessages.mockResolvedValue([asked]); + const { result } = setup(target, client); + await waitFor(() => expect(mockMessages).toHaveBeenCalled()); + expect(result.current.isLoading).toBe(true); + await act(async () => finish({ id: target.agent_id })); + await existing; + await waitFor(() => expect(result.current.isLoading).toBe(false)); + expect(mockAgent).toHaveBeenCalledTimes(1); + }); + it('reads the conversation through the ordinary messages route, as a list', async () => { mockStreamStatus.mockResolvedValue({ active: false }); mockMessages.mockResolvedValue([asked]); diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index edc45d42f0..4af3832162 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -400,6 +400,11 @@ test.describe('detached subagent activity', () => { /** 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. */ + await page.route(`**/api/agents/${children[0].id}`, async (route) => { + if (route.request().method() === 'GET') + await new Promise((resolve) => setTimeout(resolve, 500)); + await route.continue(); + }); 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(); diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx index 3195571fd9..ae3399ec80 100644 --- a/packages/chat/src/components/side/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -119,10 +119,12 @@ function setup({ chat = { conversation }, stored = [user, reply('response-1', 'It shipped.')], loadMessages = jest.fn(async () => stored), + canSubmit = () => true, }: { chat?: SideChat; stored?: TMessage[]; loadMessages?: jest.Mock>; + canSubmit?: () => boolean; } = {}) { const streams: TestStream[] = []; const sendMessages = jest.fn( @@ -155,7 +157,7 @@ function setup({ return { conversation: held, setConversation }; }, useNewConversation: () => () => undefined, - useTurnServices: () => createTurnServices(), + useTurnServices: () => createTurnServices({ canSubmit }), useAbortStream: () => () => Promise.reject(new Error('unused')), useMessageCache: () => { throw new Error('A side chat reads its own messages'); @@ -343,6 +345,29 @@ describe('SideChatPanel', () => { expect(field()).toHaveValue(''); }); + it('keeps a refused handoff as an editable draft without later automatic replay', async () => { + let allowed = false; + const { sendMessages, onHandedTextTaken, rerenderWith } = setup({ + chat: { conversation, text: 'Carry on from here.' }, + canSubmit: () => allowed, + }); + await waitFor(() => expect(field()).toHaveValue('Carry on from here.')); + expect(rows()).toContain('reply=It shipped.'); + expect(sendMessages).not.toHaveBeenCalled(); + expect(onHandedTextTaken).toHaveBeenCalledTimes(1); + fireEvent.change(field(), { target: { value: 'An edited question.' } }); + allowed = true; + rerenderWith({ conversation, text: 'Carry on from here.' }); + await settle(); + expect(field()).toHaveValue('An edited question.'); + expect(sendMessages).not.toHaveBeenCalled(); + fireEvent.change(field(), { target: { value: '' } }); + rerenderWith({ conversation, text: 'Carry on from here.' }); + await settle(); + expect(field()).toHaveValue(''); + expect(sendMessages).not.toHaveBeenCalled(); + }); + it('says when the conversation could not be loaded, and tries again', async () => { const loadMessages = jest .fn, []>() diff --git a/packages/chat/src/react/side/host.tsx b/packages/chat/src/react/side/host.tsx index 8e190cf349..a48bf5f577 100644 --- a/packages/chat/src/react/side/host.tsx +++ b/packages/chat/src/react/side/host.tsx @@ -13,7 +13,7 @@ export interface SideChatHost { * under it, and a transport that can start and stop one on the conversation's endpoint. */ useChat: ( - conversation: Pick, + conversation: Pick, options?: Pick, ) => FollowedChat; /** Opens the conversation as the page's main one. */