From 454b95e04b485eecccf34188e210e95484bdcbe6 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:28:27 -0800 Subject: [PATCH 1/7] Fix Side Chat Handoff Destination Readiness --- .../hooks/Chat/__tests__/readiness.spec.tsx | 100 +++++++++++++++ .../services.readCodeInputs.spec.tsx | 14 ++- client/src/hooks/Chat/ask/readiness.ts | 80 ++++++++++++ client/src/hooks/Chat/services.ts | 3 + e2e/specs/mock/subagent-activity.spec.ts | 19 +++ .../components/side/__tests__/panel.spec.tsx | 116 +++++++++++++++++- packages/chat/src/components/side/panel.tsx | 30 ++++- packages/chat/src/react/chat/driven.ts | 13 +- packages/chat/src/react/chat/host.tsx | 4 + packages/chat/src/react/chat/index.ts | 1 + 10 files changed, 367 insertions(+), 13 deletions(-) create mode 100644 client/src/hooks/Chat/__tests__/readiness.spec.tsx create mode 100644 client/src/hooks/Chat/ask/readiness.ts diff --git a/client/src/hooks/Chat/__tests__/readiness.spec.tsx b/client/src/hooks/Chat/__tests__/readiness.spec.tsx new file mode 100644 index 00000000000..a5ad8c86ce6 --- /dev/null +++ b/client/src/hooks/Chat/__tests__/readiness.spec.tsx @@ -0,0 +1,100 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryKeys, EModelEndpoint } from 'librechat-data-provider'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { Agent, TConversation } from 'librechat-data-provider'; +import type { ReactNode } from 'react'; +import useTargetReadiness, { getTargetReadiness } from '../ask/readiness'; + +const selected = (id: string): TConversation => + ({ + conversationId: `conversation-${id}`, + endpoint: EModelEndpoint.agents, + agent_id: id, + }) as TConversation; + +function setup(id = 'agent_1') { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() }, + }); + client.setQueryData([QueryKeys.endpoints], { + agents: {}, + openAI: {}, + assistants: { version: 'v2' }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const hook = renderHook(({ conversation }) => useTargetReadiness(conversation, null), { + wrapper, + initialProps: { conversation: selected(id) }, + }); + return { client, ...hook }; +} + +it('observes delayed destination details without starting another query', async () => { + const { client, result } = setup(); + let release: (agent: Agent) => void = () => undefined; + const request = jest.fn( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + let fetched: Promise; + act(() => { + fetched = client.fetchQuery([QueryKeys.agent, 'agent_1'], request); + }); + expect(result.current).toBe('pending'); + await act(async () => { + release({ id: 'agent_1' } as Agent); + await fetched; + }); + await waitFor(() => expect(result.current).toBe('ready')); + expect(request).toHaveBeenCalledTimes(1); +}); + +it('exposes rejected and missing destinations as blocked, not pending', async () => { + const { client, result } = setup(); + await act(async () => { + await client + .fetchQuery([QueryKeys.agent, 'agent_1'], () => Promise.reject(new Error('denied'))) + .catch(() => undefined); + }); + await waitFor(() => expect(result.current).toBe('blocked')); + act(() => { + client.setQueryData([QueryKeys.agent, 'agent_1'], null); + }); + expect(result.current).toBe('blocked'); +}); + +it('ignores a late previous destination and unrelated query updates', async () => { + const { client, result, rerender } = setup(); + rerender({ conversation: selected('agent_2') }); + act(() => { + client.setQueryData([QueryKeys.agent, 'agent_1'], { id: 'agent_1' }); + }); + expect(result.current).toBe('pending'); + act(() => { + client.setQueryData([QueryKeys.agent, 'agent_2'], { id: 'agent_2' }); + }); + await waitFor(() => expect(result.current).toBe('ready')); + act(() => { + client.setQueryData(['unrelated'], { data: true }); + }); + expect(result.current).toBe('ready'); +}); + +it('blocks unavailable endpoints and invalid saved targets', () => { + const { client } = setup(); + expect( + getTargetReadiness(client, { ...selected('agent_1'), endpoint: EModelEndpoint.google }), + ).toBe('blocked'); + expect(getTargetReadiness(client, { ...selected('agent_1'), agent_id: undefined })).toBe( + 'blocked', + ); + act(() => { + client.setQueryData([QueryKeys.agent, 'agent_1'], { id: 'different' }); + }); + expect(getTargetReadiness(client, selected('agent_1'))).toBe('blocked'); +}); diff --git a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx index 74897495e5f..a5d55807f5c 100644 --- a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx +++ b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx @@ -1,4 +1,4 @@ -import { renderHook } from '@testing-library/react'; +import { act, renderHook } from '@testing-library/react'; import { QueryKeys, EModelEndpoint } from 'librechat-data-provider'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { CodeApprovalModeInputs, CodeWorkspaceInputs } from '@librechat/chat'; @@ -129,9 +129,13 @@ describe('useTurnServices readCodeInputs', () => { expect(canSubmit?.(null)).toBe(false); expect(canSubmit?.(rendered)).toBe(true); expect(canSubmit?.(submitted)).toBe(false); - queryClient.setQueryData([QueryKeys.agent, 'agent_primary'], { id: 'agent_primary' }); + act(() => { + queryClient.setQueryData([QueryKeys.agent, 'agent_primary'], { id: 'agent_primary' }); + }); expect(canSubmit?.(submitted)).toBe(true); - queryClient.removeQueries([QueryKeys.endpoints]); + act(() => { + queryClient.removeQueries([QueryKeys.endpoints]); + }); expect(canSubmit?.(submitted)).toBe(false); }); @@ -156,7 +160,9 @@ describe('useTurnServices readCodeInputs', () => { }; rerender(); expect(canSubmit?.(submitted)).toBe(false); - queryClient.setQueryData([QueryKeys.agent, 'agent_added'], { id: 'agent_added' }); + act(() => { + queryClient.setQueryData([QueryKeys.agent, 'agent_added'], { id: 'agent_added' }); + }); expect(canSubmit?.(submitted)).toBe(true); settings = { ...settings, addedConversation: { ...added, agent_id: 'agent_other' } }; diff --git a/client/src/hooks/Chat/ask/readiness.ts b/client/src/hooks/Chat/ask/readiness.ts new file mode 100644 index 00000000000..67e31433664 --- /dev/null +++ b/client/src/hooks/Chat/ask/readiness.ts @@ -0,0 +1,80 @@ +import { useCallback, useSyncExternalStore } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { + QueryKeys, + isAgentsEndpoint, + isEphemeralAgentId, + isAssistantsEndpoint, + defaultAssistantsVersion, +} from 'librechat-data-provider'; +import type { Agent, Assistant, TConversation, TEndpointsConfig } from 'librechat-data-provider'; +import type { QueryClient, QueryKey } from '@tanstack/react-query'; +import type { TurnReadiness } from '@librechat/chat/react'; +import { assistantKey, isTargetReady } from './guards'; + +/** Observes the existing target queries; it never starts a request or selects a default. */ +export function getTargetReadiness( + client: QueryClient, + conversation: TConversation | null, +): TurnReadiness { + if (conversation == null) return 'pending'; + if (isTargetReady(client, conversation)) return 'ready'; + const endpoint = conversation.endpoint; + if (!endpoint) return 'blocked'; + const endpoints = client.getQueryState([QueryKeys.endpoints]); + if (endpoints?.status === 'error') return 'blocked'; + if (endpoints?.status !== 'success') return 'pending'; + if (!endpoints.data?.[endpoint]) return 'blocked'; + if (isAgentsEndpoint(endpoint)) { + const id = conversation.agent_id; + if (!id || isEphemeralAgentId(id)) return 'blocked'; + const target = client.getQueryState([QueryKeys.agent, id]); + return target?.status === 'success' || target?.status === 'error' ? 'blocked' : 'pending'; + } + if (isAssistantsEndpoint(endpoint)) { + if (!conversation.assistant_id) return 'blocked'; + const version = endpoints.data[endpoint].version ?? defaultAssistantsVersion[endpoint]; + const target = client.getQueryState( + assistantKey(endpoint, conversation.assistant_id, version, conversation.model), + ); + if (target?.status === 'error') return 'blocked'; + if (target?.isInvalidated) return 'pending'; + return target?.status === 'success' ? 'blocked' : 'pending'; + } + return 'blocked'; +} + +function matches(key: QueryKey, target: TConversation | null): boolean { + return ( + target != null && + ((key[0] === QueryKeys.agent && key[1] === target.agent_id) || + (key[0] === QueryKeys.assistant && + key[1] === target.endpoint && + key[2] === target.assistant_id)) + ); +} + +export default function useTargetReadiness( + conversation: TConversation | null, + added: TConversation | null, +): TurnReadiness { + const client = useQueryClient(); + const snapshot = useCallback((): TurnReadiness => { + const primary = getTargetReadiness(client, conversation); + const secondary = added == null ? 'ready' : getTargetReadiness(client, added); + if (primary === 'blocked' || secondary === 'blocked') return 'blocked'; + return primary === 'pending' || secondary === 'pending' ? 'pending' : 'ready'; + }, [client, conversation, added]); + const subscribe = useCallback( + (notify: () => void) => + client.getQueryCache().subscribe((event) => { + const key = event?.query.queryKey; + if (!key) return; + const relevant = + key[0] === QueryKeys.endpoints || matches(key, conversation) || matches(key, added); + if (relevant) notify(); + }), + [client, conversation, added], + ); + return useSyncExternalStore(subscribe, snapshot, snapshot); +} diff --git a/client/src/hooks/Chat/services.ts b/client/src/hooks/Chat/services.ts index 742b580d7f7..630ed5d0feb 100644 --- a/client/src/hooks/Chat/services.ts +++ b/client/src/hooks/Chat/services.ts @@ -22,6 +22,7 @@ import { useChatSettings } from '~/Providers/ChatSettingsContext'; import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace'; import { cancelUploads } from '~/hooks/Files/useFileHandling'; import useUserKey from '~/hooks/Input/useUserKey'; +import useTargetReadiness from './ask/readiness'; import { isTargetReady } from './ask/guards'; /** The app's side of a pane's turns: its catalogs, router, composer files, code workspace and @@ -63,6 +64,7 @@ export default function useTurnServices({ approval: codeApprovalState.readInputs, }; + const targetReadiness = useTargetReadiness(conversation, addedConversation); const readiness = useRef({ config, addedConversation }); readiness.current = { config, addedConversation }; @@ -85,6 +87,7 @@ export default function useTurnServices({ getEphemeralAgent, getUserKey: getExpiry, getRouteProjectId: getRouteChatProjectId, + readiness: config.loaded === false ? 'pending' : targetReadiness, canSubmit: (submitted) => { const { config, addedConversation } = readiness.current; return ( diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index edc45d42f04..fd677c46638 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -352,6 +352,14 @@ test.describe('detached subagent activity', () => { ]; const parentName = uniqueAgentName('E2E Side Chat Parent'); const createdAgentIds: string[] = []; + let releaseAgent: () => void = () => undefined; + const agentReady = new Promise((resolve) => { + releaseAgent = resolve; + }); + let observedAgent: () => void = () => undefined; + const agentRequested = new Promise((resolve) => { + observedAgent = resolve; + }); /** Every generation the page starts, by the conversation it is posted for. */ const starts: Array = []; page.on('request', (request) => { @@ -380,6 +388,13 @@ test.describe('detached subagent activity', () => { }); createdAgentIds.push(parent.id); + /** The destination's history can load before its selected agent details. */ + await page.route(`**/api/agents/${children[0].id}`, async (route) => { + observedAgent(); + await agentReady; + await route.continue(); + }); + await selectAgent(page, parentName); const response = await sendMessageAndWaitForCompletion( page, @@ -416,6 +431,9 @@ test.describe('detached subagent activity', () => { /** 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 agentRequested; + expect(starts.slice(startsBefore)).toEqual([]); + releaseAgent(); await expect(sideChat).toContainText('What did you find?'); await expect(sideChat).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); expect(starts.slice(startsBefore)).toEqual([sideConversationId]); @@ -441,6 +459,7 @@ test.describe('detached subagent activity', () => { await expect(main).toContainText('What did you find?'); await expect(main).toContainText('And then?'); } finally { + releaseAgent(); for (const agentId of createdAgentIds.reverse()) { await cleanupAgent(page, agentId); } diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx index 3195571fd95..e73fc8d0db8 100644 --- a/packages/chat/src/components/side/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -7,9 +7,9 @@ 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 { ChatHost, TurnServices } from '../../../react/chat/host'; 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'; @@ -119,10 +119,12 @@ function setup({ chat = { conversation }, stored = [user, reply('response-1', 'It shipped.')], loadMessages = jest.fn(async () => stored), + services = createTurnServices(), }: { chat?: SideChat; stored?: TMessage[]; loadMessages?: jest.Mock>; + services?: TurnServices; } = {}) { const streams: TestStream[] = []; const sendMessages = jest.fn( @@ -155,7 +157,7 @@ function setup({ return { conversation: held, setConversation }; }, useNewConversation: () => () => undefined, - useTurnServices: () => createTurnServices(), + useTurnServices: () => services, useAbortStream: () => () => Promise.reject(new Error('unused')), useMessageCache: () => { throw new Error('A side chat reads its own messages'); @@ -343,6 +345,116 @@ describe('SideChatPanel', () => { expect(field()).toHaveValue(''); }); + it('waits for destination readiness before consuming handed text', async () => { + let ready = false; + const services = createTurnServices({ readiness: 'pending', canSubmit: () => ready }); + const chat = { conversation, text: 'Carry on from here.' }; + const view = setup({ chat, services }); + + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(view.onHandedTextTaken).not.toHaveBeenCalled(); + + ready = true; + services.readiness = 'ready'; + view.rerenderWith(chat); + await waitFor(() => expect(view.streams).toHaveLength(1)); + expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + }); + + it.each(['blocked', 'ready'] as const)( + 'keeps a %s admission rejection as a draft without retrying it', + async (readiness) => { + let allowed = false; + const services = createTurnServices({ readiness, canSubmit: () => allowed }); + const chat = { conversation, text: 'Carry on from here.' }; + const view = setup({ chat, services }); + await waitFor(() => expect(field()).toHaveValue(chat.text)); + expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); + allowed = true; + services.readiness = 'ready'; + view.rerenderWith(chat); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(field()).toHaveValue(chat.text); + }, + ); + + it('preserves a failed destination handoff as an editable draft', async () => { + const services = createTurnServices({ readiness: 'pending', canSubmit: () => false }); + const chat = { conversation, text: 'Carry on from here.' }; + const view = setup({ chat, services }); + await waitFor(() => expect(rows()).toHaveLength(2)); + services.readiness = 'blocked'; + view.rerenderWith(chat); + await waitFor(() => expect(field()).toHaveValue(chat.text)); + expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('sends only the current destination handoff after switching while pending', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const view = setup({ chat: { conversation, text: 'Old destination.' }, services }); + await waitFor(() => expect(rows()).toHaveLength(2)); + const next = { + conversation: { ...conversation, conversationId: 'next-destination' }, + text: 'New destination.', + }; + view.rerenderWith(next); + await waitFor(() => + expect(screen.getByRole('region', { name: 'Side chat' })).toHaveAttribute( + 'data-side-chat', + 'next-destination', + ), + ); + services.readiness = 'ready'; + view.rerenderWith(next); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + expect(view.sendMessages.mock.calls[0][0].payload).toMatchObject({ + text: 'New destination.', + conversationId: 'next-destination', + }); + }); + + it.each(['ready', 'blocked'] as const)( + 'keeps an edited draft when a pending destination becomes %s', + async (readiness) => { + const services = createTurnServices({ + readiness: 'pending', + canSubmit: () => readiness === 'ready', + }); + const chat = { conversation, text: 'Original handoff.' }; + const view = setup({ chat, services }); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'My revised question.' } }); + expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); + services.readiness = readiness; + view.rerenderWith(chat); + await settle(); + expect(field()).toHaveValue('My revised question.'); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); + if (readiness === 'ready') { + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + expect(view.sendMessages.mock.calls[0][0].payload).toMatchObject({ + text: 'My revised question.', + }); + } + }, + ); + + it('does not submit a pending handoff after the panel closes', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const view = setup({ chat: { conversation, text: 'Carry on from here.' }, services }); + await waitFor(() => expect(rows()).toHaveLength(2)); + view.unmount(); + services.readiness = 'ready'; + await settle(); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(view.onHandedTextTaken).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/components/side/panel.tsx b/packages/chat/src/components/side/panel.tsx index 455b7b5967f..b7c300352b4 100644 --- a/packages/chat/src/components/side/panel.tsx +++ b/packages/chat/src/components/side/panel.tsx @@ -5,6 +5,7 @@ import { cn, Button, Composer, useLocalize, useFocusTrap } from '@librechat/clie import type { ComposerStopProps, ComposerKeyVerdict } from '@librechat/client'; import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'; import type { ChatContract } from '../../react/chat/contract'; +import type { TurnReadiness } from '../../react/chat/host'; import type { SideChat } from '../../react/side/state'; import type { SubmittedTurn } from '../../core'; import { SIDE_CHAT_PANE, sideChatDraftFamily } from '../../react/side/state'; @@ -16,6 +17,7 @@ import DrivenThread from '../pane/Driven'; type SideChatComposerProps = { contract: ChatContract; + readiness: TurnReadiness; /** The reader's unsent words, which the panel holds so they outlive the composer. */ value: string; onChange: (value: string) => void; @@ -41,6 +43,7 @@ type SideChatComposerProps = { */ function SideChatComposer({ contract, + readiness, value, onChange: setValue, conversationId, @@ -74,15 +77,33 @@ function SideChatComposer({ */ const handed = useRef(); useEffect(() => { - if (!ready || handedText == null || handedText === '' || handed.current === conversationId) { + if ( + !ready || + readiness === 'pending' || + handedText == null || + handedText === '' || + handed.current === conversationId + ) { return; } handed.current = conversationId; - if (ask({ text: handedText }) === false) { + if (readiness === 'blocked' || ask({ text: handedText }) === false) { setValue(handedText); } onHandedTextTaken(); - }, [ask, conversationId, handedText, onHandedTextTaken, ready, setValue]); + }, [ask, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue]); + + /** Editing is a new intent: a delayed handoff must not send or restore older words. */ + const change = useCallback( + (text: string) => { + if (handedText && handed.current !== conversationId) { + handed.current = conversationId; + onHandedTextTaken(); + } + setValue(text); + }, + [conversationId, handedText, onHandedTextTaken, setValue], + ); const submit = useCallback(() => { const text = value.trim(); @@ -122,7 +143,7 @@ function SideChatComposer({ ( ( + const readiness = appServices.readiness ?? 'ready'; + return useMemo( () => ({ index, + readiness, conversation, setConversation, newConversation, @@ -191,6 +197,7 @@ export function useDrivenContract({ id, followed, index }: DrivenContractOptions [ id, index, + readiness, conversation, setConversation, newConversation, diff --git a/packages/chat/src/react/chat/host.tsx b/packages/chat/src/react/chat/host.tsx index 8f488671eca..63e1d4627dc 100644 --- a/packages/chat/src/react/chat/host.tsx +++ b/packages/chat/src/react/chat/host.tsx @@ -72,6 +72,8 @@ export type TurnLogger = { * What a pane's turns need from the app: its catalogs, routing, composer files, code workspace * and logging. Getters are read when a turn is sent, so they see the app's current state. */ +export type TurnReadiness = 'pending' | 'ready' | 'blocked'; + export type TurnServices = { logger: TurnLogger; isTemporary: boolean; @@ -95,6 +97,8 @@ export type TurnServices = { * as the app holds them. The package derives the decision; see `resolveTurnCode`. */ readCodeInputs: () => TurnCodeInputs; + /** Reactive admission state for automatic handoffs; blocked targets retain a draft. */ + readiness?: TurnReadiness; /** Refuses a send until the host's configuration and selected targets are ready. */ canSubmit?: (conversation: TConversation | null) => boolean; /** Moves the pane to the route a new chat starts from. */ diff --git a/packages/chat/src/react/chat/index.ts b/packages/chat/src/react/chat/index.ts index 07aa3a4b26f..d82a1b01055 100644 --- a/packages/chat/src/react/chat/index.ts +++ b/packages/chat/src/react/chat/index.ts @@ -11,6 +11,7 @@ export type { ChatHost, TurnLogger, TurnServices, + TurnReadiness, ChatTurnsParams, ChatMessageCache, ChatMessagesQuery, From e60d162c0b3062095c83c0629a6b6d736d5cf7df Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:52:17 -0800 Subject: [PATCH 2/7] fix: Preserve Pending Side Chat Handoff Drafts --- client/src/Providers/ChatHostContext.tsx | 6 + .../hooks/Chat/__tests__/readiness.spec.tsx | 170 ++++++++--- .../services.readCodeInputs.spec.tsx | 14 +- client/src/hooks/Chat/ask/readiness.ts | 49 +-- client/src/hooks/Chat/services.ts | 3 - e2e/specs/mock/subagent-activity.spec.ts | 286 +++++++++++------- packages/chat/src/components/pane/Driven.tsx | 4 +- .../components/side/__tests__/panel.spec.tsx | 80 ++++- packages/chat/src/components/side/panel.tsx | 13 +- packages/chat/src/react/chat/driven.ts | 6 +- packages/chat/src/react/chat/host.tsx | 5 +- .../src/react/side/__tests__/state.spec.ts | 63 ++++ packages/chat/src/react/side/state.ts | 30 +- 13 files changed, 512 insertions(+), 217 deletions(-) create mode 100644 packages/chat/src/react/side/__tests__/state.spec.ts diff --git a/client/src/Providers/ChatHostContext.tsx b/client/src/Providers/ChatHostContext.tsx index 310e9535072..3836b4a2bc5 100644 --- a/client/src/Providers/ChatHostContext.tsx +++ b/client/src/Providers/ChatHostContext.tsx @@ -11,6 +11,7 @@ import { } from '~/data-provider'; import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns'; import { useChatSettings } from '~/Providers/ChatSettingsContext'; +import useTurnReadiness from '~/hooks/Chat/ask/readiness'; import useTurnServices from '~/hooks/Chat/services'; import useNewConvo from '~/hooks/useNewConvo'; @@ -114,6 +115,11 @@ export const appChatHost: ChatHost = { usePaneConversation: (index) => useChatSettings().usePaneConversationState(index), useNewConversation: (index) => useNewConvo(index).newConversation, useTurnServices, + useTurnReadiness: (conversation, enabled) => { + const { config } = useChatSettings(); + const readiness = useTurnReadiness(conversation, enabled); + return config.loaded === false ? 'pending' : readiness; + }, /** `mutateAsync` is bound once per observer; the mutation result object is fresh every * render and would defeat the contract's memo. */ useAbortStream: () => useAbortStreamMutation().mutateAsync, diff --git a/client/src/hooks/Chat/__tests__/readiness.spec.tsx b/client/src/hooks/Chat/__tests__/readiness.spec.tsx index a5ad8c86ce6..3b8e7793009 100644 --- a/client/src/hooks/Chat/__tests__/readiness.spec.tsx +++ b/client/src/hooks/Chat/__tests__/readiness.spec.tsx @@ -1,18 +1,28 @@ import { act, renderHook, waitFor } from '@testing-library/react'; -import { QueryKeys, EModelEndpoint } from 'librechat-data-provider'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { QueryKeys, EModelEndpoint, dataService } from 'librechat-data-provider'; import type { Agent, TConversation } from 'librechat-data-provider'; import type { ReactNode } from 'react'; import useTargetReadiness, { getTargetReadiness } from '../ask/readiness'; +import { useGetAgentByIdQuery } from '~/data-provider/Agents/queries'; -const selected = (id: string): TConversation => +jest.mock('librechat-data-provider', () => { + const actual = jest.requireActual('librechat-data-provider'); + return { ...actual, dataService: { ...actual.dataService, getAgentById: jest.fn() } }; +}); +const getAgent = jest.mocked(dataService.getAgentById); +beforeEach(() => getAgent.mockReset()); + +const selected = (id = 'agent_1'): TConversation => ({ conversationId: `conversation-${id}`, endpoint: EModelEndpoint.agents, agent_id: id, }) as TConversation; +const denied = Object.assign(new Error('denied'), { status: 403 }); +const detail = { id: 'agent_1' } as Agent; -function setup(id = 'agent_1') { +function setupClient() { const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() }, @@ -25,76 +35,136 @@ function setup(id = 'agent_1') { const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); - const hook = renderHook(({ conversation }) => useTargetReadiness(conversation, null), { - wrapper, - initialProps: { conversation: selected(id) }, - }); - return { client, ...hook }; + return { client, wrapper }; } -it('observes delayed destination details without starting another query', async () => { - const { client, result } = setup(); - let release: (agent: Agent) => void = () => undefined; - const request = jest.fn( +it('shares one delayed request with the existing agent metadata loader', async () => { + let release!: (value: Agent) => void; + const request = getAgent.mockImplementation( () => - new Promise((resolve) => { + new Promise((resolve) => { release = resolve; }), ); - let fetched: Promise; - act(() => { - fetched = client.fetchQuery([QueryKeys.agent, 'agent_1'], request); - }); + const { wrapper } = setupClient(); + const { result } = renderHook( + () => { + useGetAgentByIdQuery('agent_1'); + return useTargetReadiness(selected()); + }, + { wrapper }, + ); expect(result.current).toBe('pending'); - await act(async () => { - release({ id: 'agent_1' } as Agent); - await fetched; - }); + expect(request).toHaveBeenCalledTimes(1); + await act(async () => release(detail)); await waitFor(() => expect(result.current).toBe('ready')); expect(request).toHaveBeenCalledTimes(1); }); -it('exposes rejected and missing destinations as blocked, not pending', async () => { - const { client, result } = setup(); - await act(async () => { +it.each(['success', 'denial'] as const)( + 'waits for the native mount refetch after a cached error: %s', + async (outcome) => { + const { client, wrapper } = setupClient(); + client.setQueryData([QueryKeys.agent, 'agent_1'], detail, { updatedAt: Date.now() - 10000 }); await client - .fetchQuery([QueryKeys.agent, 'agent_1'], () => Promise.reject(new Error('denied'))) + .fetchQuery([QueryKeys.agent, 'agent_1'], () => Promise.reject(denied)) .catch(() => undefined); - }); - await waitFor(() => expect(result.current).toBe('blocked')); - act(() => { - client.setQueryData([QueryKeys.agent, 'agent_1'], null); - }); - expect(result.current).toBe('blocked'); + let release!: (value: Agent) => void; + let reject!: (reason: unknown) => void; + const request = getAgent.mockImplementation( + () => + new Promise((resolve, fail) => { + release = resolve; + reject = fail; + }), + ); + const seen: string[] = []; + const { result } = renderHook( + () => { + useGetAgentByIdQuery('agent_1'); + const readiness = useTargetReadiness(selected()); + seen.push(readiness); + return readiness; + }, + { wrapper }, + ); + expect(seen).not.toContain('blocked'); + expect(result.current).toBe('pending'); + expect(request).toHaveBeenCalledTimes(1); + await act(async () => (outcome === 'success' ? release(detail) : reject(denied))); + await waitFor(() => expect(result.current).toBe(outcome === 'success' ? 'ready' : 'blocked')); + expect(request).toHaveBeenCalledTimes(1); + }, +); + +it('uses cached endpoint configuration after refetch fails while the agent still loads', async () => { + const { client, wrapper } = setupClient(); + await client + .fetchQuery([QueryKeys.endpoints], () => Promise.reject(denied)) + .catch(() => undefined); + let release!: (value: Agent) => void; + getAgent.mockImplementation( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const { result } = renderHook(() => useTargetReadiness(selected()), { wrapper }); + expect(result.current).toBe('pending'); + await act(async () => release(detail)); + await waitFor(() => expect(result.current).toBe('ready')); }); -it('ignores a late previous destination and unrelated query updates', async () => { - const { client, result, rerender } = setup(); - rerender({ conversation: selected('agent_2') }); - act(() => { - client.setQueryData([QueryKeys.agent, 'agent_1'], { id: 'agent_1' }); - }); +it('adds no request for a fresh cached target or an inactive handoff', () => { + const request = getAgent; + const { client, wrapper } = setupClient(); + client.setQueryData([QueryKeys.agent, 'agent_1'], detail); + const { result, rerender } = renderHook( + ({ enabled, id }) => useTargetReadiness(selected(id), enabled), + { + wrapper, + initialProps: { enabled: true, id: 'agent_1' }, + }, + ); + expect(result.current).toBe('ready'); + rerender({ enabled: false, id: 'agent_2' }); + expect(result.current).toBe('ready'); + expect(request).not.toHaveBeenCalled(); +}); + +it('fences a previous destination and ignores unrelated cache updates', async () => { + const { wrapper, client } = setupClient(); + getAgent.mockImplementation(() => new Promise(() => undefined)); + let renders = 0; + const { result, rerender } = renderHook( + ({ id }) => { + renders++; + return useTargetReadiness(selected(id)); + }, + { + wrapper, + initialProps: { id: 'agent_1' }, + }, + ); + rerender({ id: 'agent_2' }); + act(() => client.setQueryData([QueryKeys.agent, 'agent_1'], detail)); expect(result.current).toBe('pending'); - act(() => { - client.setQueryData([QueryKeys.agent, 'agent_2'], { id: 'agent_2' }); - }); + act(() => client.setQueryData([QueryKeys.agent, 'agent_2'], { id: 'agent_2' })); await waitFor(() => expect(result.current).toBe('ready')); + const settledRenders = renders; act(() => { - client.setQueryData(['unrelated'], { data: true }); + for (let i = 0; i < 20; i++) client.setQueryData(['unrelated', i], i); }); expect(result.current).toBe('ready'); + expect(renders).toBe(settledRenders); }); it('blocks unavailable endpoints and invalid saved targets', () => { - const { client } = setup(); - expect( - getTargetReadiness(client, { ...selected('agent_1'), endpoint: EModelEndpoint.google }), - ).toBe('blocked'); - expect(getTargetReadiness(client, { ...selected('agent_1'), agent_id: undefined })).toBe( + const { client } = setupClient(); + expect(getTargetReadiness(client, { ...selected(), endpoint: EModelEndpoint.google })).toBe( 'blocked', ); - act(() => { - client.setQueryData([QueryKeys.agent, 'agent_1'], { id: 'different' }); - }); - expect(getTargetReadiness(client, selected('agent_1'))).toBe('blocked'); + expect(getTargetReadiness(client, { ...selected(), agent_id: undefined })).toBe('blocked'); + client.setQueryData([QueryKeys.agent, 'agent_1'], { id: 'different' }); + expect(getTargetReadiness(client, selected())).toBe('blocked'); }); diff --git a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx index a5d55807f5c..74897495e5f 100644 --- a/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx +++ b/client/src/hooks/Chat/__tests__/services.readCodeInputs.spec.tsx @@ -1,4 +1,4 @@ -import { act, renderHook } from '@testing-library/react'; +import { renderHook } from '@testing-library/react'; import { QueryKeys, EModelEndpoint } from 'librechat-data-provider'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { CodeApprovalModeInputs, CodeWorkspaceInputs } from '@librechat/chat'; @@ -129,13 +129,9 @@ describe('useTurnServices readCodeInputs', () => { expect(canSubmit?.(null)).toBe(false); expect(canSubmit?.(rendered)).toBe(true); expect(canSubmit?.(submitted)).toBe(false); - act(() => { - queryClient.setQueryData([QueryKeys.agent, 'agent_primary'], { id: 'agent_primary' }); - }); + queryClient.setQueryData([QueryKeys.agent, 'agent_primary'], { id: 'agent_primary' }); expect(canSubmit?.(submitted)).toBe(true); - act(() => { - queryClient.removeQueries([QueryKeys.endpoints]); - }); + queryClient.removeQueries([QueryKeys.endpoints]); expect(canSubmit?.(submitted)).toBe(false); }); @@ -160,9 +156,7 @@ describe('useTurnServices readCodeInputs', () => { }; rerender(); expect(canSubmit?.(submitted)).toBe(false); - act(() => { - queryClient.setQueryData([QueryKeys.agent, 'agent_added'], { id: 'agent_added' }); - }); + queryClient.setQueryData([QueryKeys.agent, 'agent_added'], { id: 'agent_added' }); expect(canSubmit?.(submitted)).toBe(true); settings = { ...settings, addedConversation: { ...added, agent_id: 'agent_other' } }; diff --git a/client/src/hooks/Chat/ask/readiness.ts b/client/src/hooks/Chat/ask/readiness.ts index 67e31433664..b45b6742a63 100644 --- a/client/src/hooks/Chat/ask/readiness.ts +++ b/client/src/hooks/Chat/ask/readiness.ts @@ -10,9 +10,10 @@ import { import type { Agent, Assistant, TConversation, TEndpointsConfig } from 'librechat-data-provider'; import type { QueryClient, QueryKey } from '@tanstack/react-query'; import type { TurnReadiness } from '@librechat/chat/react'; +import { useGetAgentByIdQuery } from '~/data-provider/Agents/queries'; import { assistantKey, isTargetReady } from './guards'; -/** Observes the existing target queries; it never starts a request or selects a default. */ +/** Classifies the explicit target without selecting a default or changing send admission. */ export function getTargetReadiness( client: QueryClient, conversation: TConversation | null, @@ -22,13 +23,13 @@ export function getTargetReadiness( const endpoint = conversation.endpoint; if (!endpoint) return 'blocked'; const endpoints = client.getQueryState([QueryKeys.endpoints]); - if (endpoints?.status === 'error') return 'blocked'; - if (endpoints?.status !== 'success') return 'pending'; - if (!endpoints.data?.[endpoint]) return 'blocked'; + if (!endpoints?.data) return endpoints?.status === 'error' ? 'blocked' : 'pending'; + if (!endpoints.data[endpoint]) return 'blocked'; if (isAgentsEndpoint(endpoint)) { const id = conversation.agent_id; if (!id || isEphemeralAgentId(id)) return 'blocked'; const target = client.getQueryState([QueryKeys.agent, id]); + if (target?.fetchStatus === 'fetching' || target?.fetchStatus === 'paused') return 'pending'; return target?.status === 'success' || target?.status === 'error' ? 'blocked' : 'pending'; } if (isAssistantsEndpoint(endpoint)) { @@ -54,27 +55,35 @@ function matches(key: QueryKey, target: TConversation | null): boolean { ); } +/** Only a driven handoff observes readiness. Canonical agent options give the optimistic + * mount/refetch result as well as request deduplication with the pane's tool metadata loaders. */ export default function useTargetReadiness( conversation: TConversation | null, - added: TConversation | null, + enabled = true, ): TurnReadiness { const client = useQueryClient(); - const snapshot = useCallback((): TurnReadiness => { - const primary = getTargetReadiness(client, conversation); - const secondary = added == null ? 'ready' : getTargetReadiness(client, added); - if (primary === 'blocked' || secondary === 'blocked') return 'blocked'; - return primary === 'pending' || secondary === 'pending' ? 'pending' : 'ready'; - }, [client, conversation, added]); + const agentId = + enabled && conversation?.endpoint && isAgentsEndpoint(conversation.endpoint) + ? conversation.agent_id + : undefined; + const agent = useGetAgentByIdQuery(agentId, { enabled }); + const snapshot = useCallback( + (): TurnReadiness => (enabled ? getTargetReadiness(client, conversation) : 'ready'), + [client, conversation, enabled], + ); const subscribe = useCallback( - (notify: () => void) => - client.getQueryCache().subscribe((event) => { + (notify: () => void) => { + if (!enabled) return () => undefined; + return client.getQueryCache().subscribe((event) => { const key = event?.query.queryKey; - if (!key) return; - const relevant = - key[0] === QueryKeys.endpoints || matches(key, conversation) || matches(key, added); - if (relevant) notify(); - }), - [client, conversation, added], + if (key && (key[0] === QueryKeys.endpoints || matches(key, conversation))) notify(); + }); + }, + [client, conversation, enabled], ); - return useSyncExternalStore(subscribe, snapshot, snapshot); + const readiness = useSyncExternalStore(subscribe, snapshot, snapshot); + /** An errored cached agent can be refetched on this mount before the cache reports fetching. + * Use the native observer's optimistic result, then let settled failures retain the draft. */ + if (enabled && readiness !== 'ready' && (agent.isFetching || agent.isPaused)) return 'pending'; + return readiness; } diff --git a/client/src/hooks/Chat/services.ts b/client/src/hooks/Chat/services.ts index 630ed5d0feb..742b580d7f7 100644 --- a/client/src/hooks/Chat/services.ts +++ b/client/src/hooks/Chat/services.ts @@ -22,7 +22,6 @@ import { useChatSettings } from '~/Providers/ChatSettingsContext'; import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace'; import { cancelUploads } from '~/hooks/Files/useFileHandling'; import useUserKey from '~/hooks/Input/useUserKey'; -import useTargetReadiness from './ask/readiness'; import { isTargetReady } from './ask/guards'; /** The app's side of a pane's turns: its catalogs, router, composer files, code workspace and @@ -64,7 +63,6 @@ export default function useTurnServices({ approval: codeApprovalState.readInputs, }; - const targetReadiness = useTargetReadiness(conversation, addedConversation); const readiness = useRef({ config, addedConversation }); readiness.current = { config, addedConversation }; @@ -87,7 +85,6 @@ export default function useTurnServices({ getEphemeralAgent, getUserKey: getExpiry, getRouteProjectId: getRouteChatProjectId, - readiness: config.loaded === false ? 'pending' : targetReadiness, canSubmit: (submitted) => { const { config, addedConversation } = readiness.current; return ( diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index fd677c46638..1441f3d8a67 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, + conversationRow, MOCK_REPLY_TEXT, messagesView, requestJson, @@ -340,131 +341,188 @@ 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[] = []; - let releaseAgent: () => void = () => undefined; - const agentReady = new Promise((resolve) => { - releaseAgent = resolve; - }); - let observedAgent: () => void = () => undefined; - const agentRequested = new Promise((resolve) => { - observedAgent = resolve; - }); - /** 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); + for (const action of ['send', 'promote', 'close', 'switch'] as const) { + test(`continues a finished child and preserves pending words on ${action} @scenario:subagent-continue-opens-side-chat-${action}`, 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[] = []; + let releaseAgent: () => void = () => undefined; + const agentReady = new Promise((resolve) => { + releaseAgent = resolve; + }); + let observedAgent: () => void = () => undefined; + const agentRequested = new Promise((resolve) => { + observedAgent = resolve; + }); + /** 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); - /** The destination's history can load before its selected agent details. */ - await page.route(`**/api/agents/${children[0].id}`, async (route) => { - observedAgent(); - await agentReady; - await route.continue(); - }); + 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; + /** The destination's history can load before its selected agent details. */ + await page.route(`**/api/agents/${children[0].id}`, async (route) => { + observedAgent(); + await agentReady; + await route.continue(); + }); - 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, - }); + 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; - /** 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(); + 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, + }); - 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); + /** 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(); - /** 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 agentRequested; - expect(starts.slice(startsBefore)).toEqual([]); - releaseAgent(); - await expect(sideChat).toContainText('What did you find?'); - await expect(sideChat).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); - expect(starts.slice(startsBefore)).toEqual([sideConversationId]); + 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); - /** 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 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 agentRequested; + expect(starts.slice(startsBefore)).toEqual([]); + await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue( + 'What did you find?', + ); + if (action !== 'send') { + const agentResponse = page.waitForResponse( + (response) => new URL(response.url()).pathname === `/api/agents/${children[0].id}`, + ); + if (action === 'promote') { + await sideChat.getByRole('button', { name: 'Open as the main chat' }).click(); + await expect(page).toHaveURL(new RegExp(`/c/${sideConversationId}$`)); + } else if (action === 'close') { + await sideChat.getByRole('button', { name: 'Close' }).click(); + } else { + await cards.nth(1).click(); + await expect(panel).toContainText(`E2E detached child 2 complete ${label}`, { + timeout: 30_000, + }); + await panel + .getByRole('textbox', { name: 'Message input' }) + .fill('A different question.'); + await panel.getByRole('button', { name: 'Continue in a new chat' }).click(); + await expect(sideChat).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); + const otherId = await sideChat.getAttribute('data-side-chat'); + expect(otherId).not.toBe(sideConversationId); + expect(starts.slice(startsBefore)).toEqual([otherId]); + await sideChat.getByRole('button', { name: 'Close' }).click(); + } + await expect(sideChat).toHaveCount(0); + releaseAgent(); + await agentResponse; + expect(starts.slice(startsBefore)).not.toContain(sideConversationId); + if (action !== 'promote') { + await openChatHistory(page); + const row = conversationRow( + page, + `${new URL(page.url()).origin}/c/${sideConversationId}`, + ); + await row.hover(); + await row.getByRole('button', { name: 'Conversation Menu Options' }).click(); + await page.getByRole('menuitem', { name: 'Open beside chat' }).click(); + await expect(sideChat).toBeVisible(); + } + const destination = action === 'promote' ? page.getByRole('main') : sideChat; + const draft = destination.getByRole('textbox', { name: 'Message input' }); + await expect(draft).toHaveValue('What did you find?'); + await expect(destination.getByRole('button', { name: 'Send message' })).toBeEnabled(); + expect(starts.slice(startsBefore)).not.toContain(sideConversationId); + await draft.press('Enter'); + await expect(destination).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); + expect(starts.slice(startsBefore).filter((id) => id === sideConversationId)).toEqual([ + sideConversationId, + ]); + await expect(draft).toHaveValue(''); + return; + } + releaseAgent(); + await expect(sideChat).toContainText('What did you find?'); + await expect(sideChat).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); + expect(starts.slice(startsBefore)).toEqual([sideConversationId]); - /** 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 { - releaseAgent(); - for (const agentId of createdAgentIds.reverse()) { - await cleanupAgent(page, agentId); + /** 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 { + releaseAgent(); + 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/packages/chat/src/components/pane/Driven.tsx b/packages/chat/src/components/pane/Driven.tsx index 4aebd7fa6ed..db6ac58bf49 100644 --- a/packages/chat/src/components/pane/Driven.tsx +++ b/packages/chat/src/components/pane/Driven.tsx @@ -10,6 +10,7 @@ export type DrivenThreadProps = { followed: FollowedChat; /** The pane the host keys this chat's state by; see `useDrivenContract`. */ index: number; + handoff?: boolean; slots?: ChatScreenMessagesSlots; /** Drawn under the list, inside the chat's contract: the surface's composer. */ children?: (contract: ReturnType) => ReactElement | null; @@ -24,10 +25,11 @@ export default function DrivenThread({ id, followed, index, + handoff, slots, children, }: DrivenThreadProps): ReactElement { - const contract = useDrivenContract({ id, followed, index }); + const contract = useDrivenContract({ id, followed, index, handoff }); return ( <> diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx index e73fc8d0db8..3365b56c1d1 100644 --- a/packages/chat/src/components/side/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -10,8 +10,9 @@ import type { ChatStream, ChatTransport, ChatSendRequest } from '../../../core'; import type { ChatHost, TurnServices } from '../../../react/chat/host'; import type { SideChatHost } from '../../../react/side/host'; import type { SideChat } from '../../../react/side/state'; +import { createTurnServices as createBaseTurnServices } from '../../../react/chat/__fixtures__/services'; import { MessagesHostProvider, useMessagesHost } from '../../../react/messages/host'; -import { createTurnServices } from '../../../react/chat/__fixtures__/services'; +import { sideChatAtom, sideChatDraftFamily } from '../../../react/side/state'; import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; import { ChatSurfaceProvider } from '../../../react/subagents/provider'; import { createMessagesHost } from '../../../__fixtures__/messagesHost'; @@ -22,6 +23,12 @@ import { initEnglish } from '../../../__fixtures__/i18n'; import { useFollowChat } from '../../../react/follow'; import SideChatPanel from '../panel'; +type TestServices = TurnServices & { readiness?: 'pending' | 'ready' | 'blocked' }; +const createTurnServices = (overrides: Partial = {}): TestServices => ({ + ...createBaseTurnServices(), + ...overrides, +}); + beforeAll(initEnglish); const conversationId = 'side-conversation'; @@ -117,14 +124,16 @@ const partsHost = createMessagePartsHost({ function setup({ chat = { conversation }, + draft, stored = [user, reply('response-1', 'It shipped.')], loadMessages = jest.fn(async () => stored), services = createTurnServices(), }: { chat?: SideChat; + draft?: string; stored?: TMessage[]; loadMessages?: jest.Mock>; - services?: TurnServices; + services?: TestServices; } = {}) { const streams: TestStream[] = []; const sendMessages = jest.fn( @@ -158,6 +167,7 @@ function setup({ }, useNewConversation: () => () => undefined, useTurnServices: () => services, + useTurnReadiness: () => services.readiness ?? 'ready', useAbortStream: () => () => Promise.reject(new Error('unused')), useMessageCache: () => { throw new Error('A side chat reads its own messages'); @@ -170,6 +180,8 @@ function setup({ const handOffComposerText = jest.fn(); const queryClient = new QueryClient(); const store = createStore(); + if (draft != null) store.set(sideChatDraftFamily(conversationId), draft); + store.set(sideChatAtom, chat); const tree = (current: SideChat) => ( @@ -207,7 +219,11 @@ function setup({ const view = render(tree(chat)); return { ...view, - rerenderWith: (next: SideChat) => view.rerender(tree(next)), + store, + rerenderWith: (next: SideChat) => { + act(() => store.set(sideChatAtom, next)); + view.rerender(tree(next)); + }, /** Draws the panel again from nothing, as the layout does when it moves it. */ remount: () => { view.unmount(); @@ -444,6 +460,64 @@ describe('SideChatPanel', () => { }, ); + it('preserves an existing draft instead of automatically sending different handed words', async () => { + const view = setup({ + chat: { conversation, text: 'New handoff.' }, + draft: 'My existing draft.', + }); + await waitFor(() => expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1)); + expect(field()).toHaveValue('My existing draft.'); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('keeps a deliberately cleared draft empty after readiness arrives', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const chat = { conversation, text: 'Original handoff.' }; + const view = setup({ chat, services }); + await waitFor(() => expect(field()).toHaveValue(chat.text)); + fireEvent.change(field(), { target: { value: '' } }); + services.readiness = 'ready'; + view.rerenderWith(chat); + await settle(); + expect(field()).toHaveValue(''); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('keeps pending words when promoted before history has loaded', async () => { + const chat = { conversation, text: 'Keep these words.' }; + const view = setup({ chat, loadMessages: jest.fn(() => new Promise(() => undefined)) }); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe(chat.text); + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + expect(view.handOffComposerText).toHaveBeenCalledWith(conversationId, chat.text); + expect(view.onClose).toHaveBeenCalledTimes(1); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('keeps a pending draft on switch and ordinary reopen without automatic submission', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const view = setup({ chat: { conversation, text: 'Keep these words.' }, services }); + await waitFor(() => expect(rows()).toHaveLength(2)); + view.rerenderWith({ conversation: { ...conversation, conversationId: 'other' } }); + services.readiness = 'ready'; + view.rerenderWith({ conversation }); + await waitFor(() => expect(field()).toHaveValue('Keep these words.')); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('does not duplicate a deliberate manual send while automatic readiness is pending', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const chat = { conversation, text: 'Send now.' }; + const view = setup({ chat, services }); + await waitFor(() => expect(screen.getByTestId('composer-send-button')).toBeEnabled()); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + services.readiness = 'ready'; + view.rerenderWith(chat); + await settle(); + expect(view.sendMessages).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + }); + it('does not submit a pending handoff after the panel closes', async () => { const services = createTurnServices({ readiness: 'pending' }); const view = setup({ chat: { conversation, text: 'Carry on from here.' }, services }); diff --git a/packages/chat/src/components/side/panel.tsx b/packages/chat/src/components/side/panel.tsx index b7c300352b4..dcba995d9a4 100644 --- a/packages/chat/src/components/side/panel.tsx +++ b/packages/chat/src/components/side/panel.tsx @@ -87,11 +87,11 @@ function SideChatComposer({ return; } handed.current = conversationId; - if (readiness === 'blocked' || ask({ text: handedText }) === false) { - setValue(handedText); + if (value === handedText && readiness === 'ready' && ask({ text: handedText }) !== false) { + setValue(''); } onHandedTextTaken(); - }, [ask, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue]); + }, [ask, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue, value]); /** Editing is a new intent: a delayed handoff must not send or restore older words. */ const change = useCallback( @@ -269,7 +269,12 @@ export default function SideChatPanel({ ); } else { body = ( - + {(contract) => ( undefined; +const useReady = (): TurnReadiness => 'ready'; /** Where the tail sits in its thread, which a streamed delta does not change. */ const pickTailPlace = (tail: TMessage | null): Pick | null => @@ -47,6 +49,7 @@ export function useDrivenContract({ id, followed, index, + handoff = false, }: DrivenContractOptions): ChatContract & { readiness: TurnReadiness } { const host = useChatHost(); const { chat, status, isLoading, isFollowing, canSend, send, stop } = followed; @@ -156,7 +159,8 @@ export function useDrivenContract({ const [optionSettings, setOptionSettings] = useAtom(optionSettingsFamily(index)); const feedbackEnabled = host.useFeedbackEnabled(); - const readiness = appServices.readiness ?? 'ready'; + const useReadiness = host.useTurnReadiness ?? useReady; + const readiness = useReadiness(conversation, handoff); return useMemo( () => ({ index, diff --git a/packages/chat/src/react/chat/host.tsx b/packages/chat/src/react/chat/host.tsx index 63e1d4627dc..d38cfebc520 100644 --- a/packages/chat/src/react/chat/host.tsx +++ b/packages/chat/src/react/chat/host.tsx @@ -97,8 +97,6 @@ export type TurnServices = { * as the app holds them. The package derives the decision; see `resolveTurnCode`. */ readCodeInputs: () => TurnCodeInputs; - /** Reactive admission state for automatic handoffs; blocked targets retain a draft. */ - readiness?: TurnReadiness; /** Refuses a send until the host's configuration and selected targets are ready. */ canSubmit?: (conversation: TConversation | null) => boolean; /** Moves the pane to the route a new chat starts from. */ @@ -164,6 +162,9 @@ export interface ChatHost { useNewConversation(index: number): ChatContract['newConversation']; /** What the pane's turns need from the app; see {@link TurnServices}. */ useTurnServices(params: ChatTurnsParams): TurnServices; + /** Reactive admission for a driven pane's automatic handoff. Optional hosts default ready; + * the hook is always called in driven panes, with queries enabled only for a handoff. */ + useTurnReadiness?: (conversation: TConversation | null, enabled: boolean) => TurnReadiness; /** Stops a resumable generation. */ useAbortStream(): (params: AbortStreamParams) => Promise; useMessageCache(): ChatMessageCache; diff --git a/packages/chat/src/react/side/__tests__/state.spec.ts b/packages/chat/src/react/side/__tests__/state.spec.ts new file mode 100644 index 00000000000..e0798439b94 --- /dev/null +++ b/packages/chat/src/react/side/__tests__/state.spec.ts @@ -0,0 +1,63 @@ +import { createStore } from 'jotai'; +import type { TConversation } from 'librechat-data-provider'; +import { sideChatAtom, sideChatDraftFamily, sideChatRequestAtom } from '../state'; + +const conversation = { conversationId: 'destination' } as TConversation; + +it('seeds a handoff synchronously and preserves it across close and ordinary reopen', () => { + const store = createStore(); + store.set(sideChatAtom, { conversation, text: 'My question.' }); + expect(store.get(sideChatDraftFamily('destination'))).toBe('My question.'); + store.set(sideChatAtom, null); + store.set(sideChatAtom, { conversation }); + expect(store.get(sideChatDraftFamily('destination'))).toBe('My question.'); + expect(store.get(sideChatAtom)?.text).toBeUndefined(); +}); + +it.each(['An existing draft.', ''])( + 'does not reseed an edited or cleared draft during functional refinement: %s', + (draft) => { + const store = createStore(); + store.set(sideChatAtom, { conversation, text: 'Original handoff.' }); + store.set(sideChatDraftFamily('destination'), draft); + store.set( + sideChatAtom, + (current) => + current && { ...current, conversation: { ...conversation, title: 'Loaded title' } }, + ); + expect(store.get(sideChatDraftFamily('destination'))).toBe(draft); + store.set(sideChatAtom, (current) => current && { conversation: current.conversation }); + expect(store.get(sideChatDraftFamily('destination'))).toBe(draft); + }, +); + +it('preserves an existing draft when another handoff opens the same conversation', () => { + const store = createStore(); + store.set(sideChatDraftFamily('destination'), 'My existing words.'); + store.set(sideChatAtom, { conversation, text: 'New handoff.' }); + expect(store.get(sideChatDraftFamily('destination'))).toBe('My existing words.'); +}); + +it('separates destinations, withdraws stale open requests, and keeps drafts in memory only', () => { + const store = createStore(); + const request = {}; + store.set(sideChatRequestAtom, request); + store.set(sideChatAtom, { conversation, text: 'First.' }); + expect(store.get(sideChatRequestAtom)).toBeNull(); + store.set(sideChatAtom, { + conversation: { conversationId: 'other' } as TConversation, + text: 'Second.', + }); + expect(store.get(sideChatDraftFamily('destination'))).toBe('First.'); + expect(store.get(sideChatDraftFamily('other'))).toBe('Second.'); + expect(createStore().get(sideChatDraftFamily('destination'))).toBe(''); +}); + +it('does not seed a shared empty-id draft for an invalid destination', () => { + const store = createStore(); + store.set(sideChatAtom, { + conversation: { conversationId: '' } as TConversation, + text: 'Not a destination.', + }); + expect(store.get(sideChatDraftFamily(''))).toBe(''); +}); diff --git a/packages/chat/src/react/side/state.ts b/packages/chat/src/react/side/state.ts index e048938e71a..8302124a45d 100644 --- a/packages/chat/src/react/side/state.ts +++ b/packages/chat/src/react/side/state.ts @@ -47,6 +47,15 @@ const shownSideChatAtom = atom(null); */ export const sideChatRequestAtom: 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(''), +); + /** The side chat on screen, if any. One at a time: it takes the page's side panel. */ export const sideChatAtom: WritableAtom], void> = atom( @@ -58,15 +67,18 @@ export const sideChatAtom: WritableAtom PrimitiveAtom = atomFamily( - (_conversationId: string) => atom(''), -); From 30cfdc7e61678bb39fe36a5a8a6693cf0dcafb29 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:44:30 -0800 Subject: [PATCH 3/7] fix: Preserve Side Chat Handoff Ownership Through Lifecycle Changes --- .../hooks/Chat/__tests__/readiness.spec.tsx | 46 +++++- client/src/hooks/Chat/ask/readiness.ts | 12 +- e2e/specs/mock/subagent-activity.spec.ts | 81 ++++++++-- .../components/side/__tests__/panel.spec.tsx | 139 ++++++++++++++---- packages/chat/src/components/side/panel.tsx | 20 ++- .../src/react/chat/__tests__/driven.spec.tsx | 40 ++++- packages/chat/src/react/follow.ts | 2 +- .../src/react/side/__tests__/state.spec.ts | 41 ++++++ packages/chat/src/react/side/state.ts | 20 ++- 9 files changed, 338 insertions(+), 63 deletions(-) diff --git a/client/src/hooks/Chat/__tests__/readiness.spec.tsx b/client/src/hooks/Chat/__tests__/readiness.spec.tsx index 3b8e7793009..54edff5b617 100644 --- a/client/src/hooks/Chat/__tests__/readiness.spec.tsx +++ b/client/src/hooks/Chat/__tests__/readiness.spec.tsx @@ -97,6 +97,40 @@ it.each(['success', 'denial'] as const)( }, ); +it.each(['success', 'denial'] as const)( + 'waits for the native mount refetch after cached success: %s', + async (outcome) => { + const { client, wrapper } = setupClient(); + client.setQueryData([QueryKeys.agent, 'agent_1'], detail, { updatedAt: Date.now() - 10000 }); + let release!: (value: Agent) => void; + let reject!: (reason: unknown) => void; + const request = getAgent.mockImplementation( + () => + new Promise((resolve, fail) => { + release = resolve; + reject = fail; + }), + ); + const seen: string[] = []; + const { result } = renderHook( + () => { + useGetAgentByIdQuery('agent_1'); + const readiness = useTargetReadiness(selected()); + seen.push(readiness); + return readiness; + }, + { wrapper }, + ); + expect(seen).not.toContain('blocked'); + expect(seen).not.toContain('ready'); + expect(result.current).toBe('pending'); + expect(request).toHaveBeenCalledTimes(1); + await act(async () => (outcome === 'success' ? release(detail) : reject(denied))); + await waitFor(() => expect(result.current).toBe(outcome === 'success' ? 'ready' : 'blocked')); + expect(request).toHaveBeenCalledTimes(1); + }, +); + it('uses cached endpoint configuration after refetch fails while the agent still loads', async () => { const { client, wrapper } = setupClient(); await client @@ -134,7 +168,13 @@ it('adds no request for a fresh cached target or an inactive handoff', () => { it('fences a previous destination and ignores unrelated cache updates', async () => { const { wrapper, client } = setupClient(); - getAgent.mockImplementation(() => new Promise(() => undefined)); + const releases = new Map void>(); + getAgent.mockImplementation( + ({ agent_id }) => + new Promise((resolve) => { + releases.set(agent_id, resolve); + }), + ); let renders = 0; const { result, rerender } = renderHook( ({ id }) => { @@ -147,9 +187,9 @@ it('fences a previous destination and ignores unrelated cache updates', async () }, ); rerender({ id: 'agent_2' }); - act(() => client.setQueryData([QueryKeys.agent, 'agent_1'], detail)); + await act(async () => releases.get('agent_1')?.(detail)); expect(result.current).toBe('pending'); - act(() => client.setQueryData([QueryKeys.agent, 'agent_2'], { id: 'agent_2' })); + await act(async () => releases.get('agent_2')?.({ id: 'agent_2' } as Agent)); await waitFor(() => expect(result.current).toBe('ready')); const settledRenders = renders; act(() => { diff --git a/client/src/hooks/Chat/ask/readiness.ts b/client/src/hooks/Chat/ask/readiness.ts index b45b6742a63..ba4f8183aae 100644 --- a/client/src/hooks/Chat/ask/readiness.ts +++ b/client/src/hooks/Chat/ask/readiness.ts @@ -19,7 +19,7 @@ export function getTargetReadiness( conversation: TConversation | null, ): TurnReadiness { if (conversation == null) return 'pending'; - if (isTargetReady(client, conversation)) return 'ready'; + const ready = isTargetReady(client, conversation); const endpoint = conversation.endpoint; if (!endpoint) return 'blocked'; const endpoints = client.getQueryState([QueryKeys.endpoints]); @@ -27,11 +27,13 @@ export function getTargetReadiness( if (!endpoints.data[endpoint]) return 'blocked'; if (isAgentsEndpoint(endpoint)) { const id = conversation.agent_id; - if (!id || isEphemeralAgentId(id)) return 'blocked'; + if (!id || isEphemeralAgentId(id)) return ready ? 'ready' : 'blocked'; const target = client.getQueryState([QueryKeys.agent, id]); if (target?.fetchStatus === 'fetching' || target?.fetchStatus === 'paused') return 'pending'; + if (ready) return 'ready'; return target?.status === 'success' || target?.status === 'error' ? 'blocked' : 'pending'; } + if (ready) return 'ready'; if (isAssistantsEndpoint(endpoint)) { if (!conversation.assistant_id) return 'blocked'; const version = endpoints.data[endpoint].version ?? defaultAssistantsVersion[endpoint]; @@ -82,8 +84,8 @@ export default function useTargetReadiness( [client, conversation, enabled], ); const readiness = useSyncExternalStore(subscribe, snapshot, snapshot); - /** An errored cached agent can be refetched on this mount before the cache reports fetching. - * Use the native observer's optimistic result, then let settled failures retain the draft. */ - if (enabled && readiness !== 'ready' && (agent.isFetching || agent.isPaused)) return 'pending'; + /** A stale success or cached error can refetch on mount before the cache reports fetching. + * Wait for that native attempt; only its settled result may consume the handoff. */ + if (enabled && (agent.isFetching || agent.isPaused)) return 'pending'; return readiness; } diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index 1441f3d8a67..9f024fe0cf0 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -341,12 +341,22 @@ test.describe('detached subagent activity', () => { } }); - for (const action of ['send', 'promote', 'close', 'switch'] as const) { + for (const action of [ + 'send', + 'promote', + 'promote-clear', + 'close', + 'switch', + 'refetch-success', + 'refetch-denial', + ] as const) { test(`continues a finished child and preserves pending words on ${action} @scenario:subagent-continue-opens-side-chat-${action}`, async ({ page, }) => { test.setTimeout(120_000); const label = `beside-${Date.now().toString(36)}`; + const refetch = action === 'refetch-success' || action === 'refetch-denial'; + const promote = action === 'promote' || action === 'promote-clear'; /** The fixture's parent dispatches exactly two children; the first is the one continued. */ const childNames = [ uniqueAgentName('E2E Side Chat Child A'), @@ -390,11 +400,27 @@ test.describe('detached subagent activity', () => { }); createdAgentIds.push(parent.id); + /** Warm the canonical query through its ordinary UI before testing stale success. */ + if (refetch) { + const warm = page.waitForResponse( + (response) => new URL(response.url()).pathname === `/api/agents/${children[0].id}`, + ); + await selectAgent(page, childNames[0]); + expect((await warm).ok()).toBeTruthy(); + } /** The destination's history can load before its selected agent details. */ await page.route(`**/api/agents/${children[0].id}`, async (route) => { + if (route.request().method() !== 'GET') { + await route.continue(); + return; + } observedAgent(); await agentReady; - await route.continue(); + if (action === 'refetch-denial') { + await route.fulfill({ status: 403, json: { message: 'Agent access denied.' } }); + } else { + await route.continue(); + } }); await selectAgent(page, parentName); @@ -418,6 +444,7 @@ 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. */ const startsBefore = starts.length; + if (refetch) await page.clock.setFixedTime(new Date(Date.now() + 6000)); await panel.getByRole('textbox', { name: 'Message input' }).fill('What did you find?'); await panel.getByRole('button', { name: 'Continue in a new chat' }).click(); @@ -438,11 +465,24 @@ test.describe('detached subagent activity', () => { await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue( 'What did you find?', ); - if (action !== 'send') { + if (action === 'refetch-denial') { + const denied = page.waitForResponse( + (response) => new URL(response.url()).pathname === `/api/agents/${children[0].id}`, + ); + releaseAgent(); + expect((await denied).status()).toBe(403); + const draft = sideChat.getByRole('textbox', { name: 'Message input' }); + await expect(draft).toHaveValue('What did you find?'); + await sideChat.getByRole('button', { name: 'Send message' }).click(); + await expect(draft).toHaveValue('What did you find?'); + expect(starts.slice(startsBefore)).toEqual([]); + return; + } + if (action !== 'send' && !refetch) { const agentResponse = page.waitForResponse( (response) => new URL(response.url()).pathname === `/api/agents/${children[0].id}`, ); - if (action === 'promote') { + if (promote) { await sideChat.getByRole('button', { name: 'Open as the main chat' }).click(); await expect(page).toHaveURL(new RegExp(`/c/${sideConversationId}$`)); } else if (action === 'close') { @@ -466,7 +506,7 @@ test.describe('detached subagent activity', () => { releaseAgent(); await agentResponse; expect(starts.slice(startsBefore)).not.toContain(sideConversationId); - if (action !== 'promote') { + if (!promote) { await openChatHistory(page); const row = conversationRow( page, @@ -477,17 +517,36 @@ test.describe('detached subagent activity', () => { await page.getByRole('menuitem', { name: 'Open beside chat' }).click(); await expect(sideChat).toBeVisible(); } - const destination = action === 'promote' ? page.getByRole('main') : sideChat; + const destination = promote ? page.getByRole('main') : sideChat; const draft = destination.getByRole('textbox', { name: 'Message input' }); await expect(draft).toHaveValue('What did you find?'); await expect(destination.getByRole('button', { name: 'Send message' })).toBeEnabled(); expect(starts.slice(startsBefore)).not.toContain(sideConversationId); - await draft.press('Enter'); - await expect(destination).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); - expect(starts.slice(startsBefore).filter((id) => id === sideConversationId)).toEqual([ - sideConversationId, - ]); + if (action === 'promote-clear') { + await draft.fill(''); + } else { + await draft.press('Enter'); + await expect(destination).toContainText(MOCK_REPLY_TEXT, { timeout: 30_000 }); + expect(starts.slice(startsBefore).filter((id) => id === sideConversationId)).toEqual([ + sideConversationId, + ]); + } await expect(draft).toHaveValue(''); + if (promote) { + /** SPA navigation keeps the same draft store: a reload would conceal a stale copy. */ + await openChatHistory(page); + await conversationRow(page, `${new URL(page.url()).origin}${parentPath}`).click(); + await expect(page).toHaveURL(new RegExp(`${parentPath}$`)); + const row = conversationRow( + page, + `${new URL(page.url()).origin}/c/${sideConversationId}`, + ); + await row.hover(); + await row.getByRole('button', { name: 'Conversation Menu Options' }).click(); + await page.getByRole('menuitem', { name: 'Open beside chat' }).click(); + await expect(sideChat).toBeVisible(); + await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue(''); + } return; } releaseAgent(); diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx index 3365b56c1d1..5ce57238e23 100644 --- a/packages/chat/src/components/side/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -182,7 +182,25 @@ function setup({ const store = createStore(); if (draft != null) store.set(sideChatDraftFamily(conversationId), draft); store.set(sideChatAtom, chat); - const tree = (current: SideChat) => ( + /** The real owner renders normalized state and consumes intent/close in that same store. */ + const Pane = () => { + const [current, setCurrent] = useAtom(sideChatAtom); + return current == null ? null : ( + { + onClose(); + setCurrent(null); + }} + onHandedTextTaken={() => { + onHandedTextTaken(); + setCurrent((value) => value && { conversation: value.conversation }); + }} + /> + ); + }; + const tree = () => ( - onHandedTextTaken()} - /> + @@ -216,18 +230,16 @@ function setup({ ); - const view = render(tree(chat)); + const view = render(tree()); return { ...view, store, - rerenderWith: (next: SideChat) => { - act(() => store.set(sideChatAtom, next)); - view.rerender(tree(next)); - }, + open: (next: SideChat) => act(() => store.set(sideChatAtom, next)), + refresh: () => view.rerender(tree()), /** Draws the panel again from nothing, as the layout does when it moves it. */ remount: () => { view.unmount(); - return render(tree(chat)); + return render(tree()); }, streams, sendMessages, @@ -341,7 +353,7 @@ describe('SideChatPanel', () => { }); it('sends the words handed over with the conversation once, as its next turn', async () => { - const { sendMessages, streams, onHandedTextTaken, rerenderWith } = setup({ + const { sendMessages, streams, onHandedTextTaken, refresh } = setup({ chat: { conversation, text: 'Carry on from here.' }, }); @@ -353,8 +365,8 @@ describe('SideChatPanel', () => { 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.' }); + /** Rendering again cannot recreate consumed intent. */ + refresh(); await settle(); expect(sendMessages).toHaveBeenCalledTimes(1); expect(onHandedTextTaken).toHaveBeenCalledTimes(1); @@ -373,7 +385,7 @@ describe('SideChatPanel', () => { ready = true; services.readiness = 'ready'; - view.rerenderWith(chat); + view.refresh(); await waitFor(() => expect(view.streams).toHaveLength(1)); expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); expect(field()).toHaveValue(''); @@ -390,7 +402,7 @@ describe('SideChatPanel', () => { expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); allowed = true; services.readiness = 'ready'; - view.rerenderWith(chat); + view.refresh(); expect(view.sendMessages).not.toHaveBeenCalled(); expect(field()).toHaveValue(chat.text); }, @@ -402,7 +414,7 @@ describe('SideChatPanel', () => { const view = setup({ chat, services }); await waitFor(() => expect(rows()).toHaveLength(2)); services.readiness = 'blocked'; - view.rerenderWith(chat); + view.refresh(); await waitFor(() => expect(field()).toHaveValue(chat.text)); expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); expect(view.sendMessages).not.toHaveBeenCalled(); @@ -416,7 +428,7 @@ describe('SideChatPanel', () => { conversation: { ...conversation, conversationId: 'next-destination' }, text: 'New destination.', }; - view.rerenderWith(next); + view.open(next); await waitFor(() => expect(screen.getByRole('region', { name: 'Side chat' })).toHaveAttribute( 'data-side-chat', @@ -424,7 +436,7 @@ describe('SideChatPanel', () => { ), ); services.readiness = 'ready'; - view.rerenderWith(next); + view.refresh(); await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); expect(view.sendMessages.mock.calls[0][0].payload).toMatchObject({ text: 'New destination.', @@ -445,7 +457,7 @@ describe('SideChatPanel', () => { fireEvent.change(field(), { target: { value: 'My revised question.' } }); expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1); services.readiness = readiness; - view.rerenderWith(chat); + view.refresh(); await settle(); expect(field()).toHaveValue('My revised question.'); expect(view.sendMessages).not.toHaveBeenCalled(); @@ -465,8 +477,7 @@ describe('SideChatPanel', () => { chat: { conversation, text: 'New handoff.' }, draft: 'My existing draft.', }); - await waitFor(() => expect(view.onHandedTextTaken).toHaveBeenCalledTimes(1)); - expect(field()).toHaveValue('My existing draft.'); + await waitFor(() => expect(field()).toHaveValue('My existing draft.')); expect(view.sendMessages).not.toHaveBeenCalled(); }); @@ -477,7 +488,7 @@ describe('SideChatPanel', () => { await waitFor(() => expect(field()).toHaveValue(chat.text)); fireEvent.change(field(), { target: { value: '' } }); services.readiness = 'ready'; - view.rerenderWith(chat); + view.refresh(); await settle(); expect(field()).toHaveValue(''); expect(view.sendMessages).not.toHaveBeenCalled(); @@ -485,11 +496,16 @@ describe('SideChatPanel', () => { it('keeps pending words when promoted before history has loaded', async () => { const chat = { conversation, text: 'Keep these words.' }; - const view = setup({ chat, loadMessages: jest.fn(() => new Promise(() => undefined)) }); + const loadMessages = jest.fn, []>(() => new Promise(() => undefined)); + const view = setup({ chat, loadMessages }); expect(view.store.get(sideChatDraftFamily(conversationId))).toBe(chat.text); fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); expect(view.handOffComposerText).toHaveBeenCalledWith(conversationId, chat.text); expect(view.onClose).toHaveBeenCalledTimes(1); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe(''); + loadMessages.mockResolvedValue([user, reply('response-1', 'It shipped.')]); + view.open({ conversation }); + await waitFor(() => expect(field()).toHaveValue('')); expect(view.sendMessages).not.toHaveBeenCalled(); }); @@ -497,9 +513,9 @@ describe('SideChatPanel', () => { const services = createTurnServices({ readiness: 'pending' }); const view = setup({ chat: { conversation, text: 'Keep these words.' }, services }); await waitFor(() => expect(rows()).toHaveLength(2)); - view.rerenderWith({ conversation: { ...conversation, conversationId: 'other' } }); + view.open({ conversation: { ...conversation, conversationId: 'other' } }); services.readiness = 'ready'; - view.rerenderWith({ conversation }); + view.open({ conversation }); await waitFor(() => expect(field()).toHaveValue('Keep these words.')); expect(view.sendMessages).not.toHaveBeenCalled(); }); @@ -512,12 +528,75 @@ describe('SideChatPanel', () => { fireEvent.click(screen.getByTestId('composer-send-button')); await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); services.readiness = 'ready'; - view.rerenderWith(chat); + view.refresh(); + await settle(); + expect(view.sendMessages).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + }); + + it('does not re-arm an accepted manual handoff when its withdrawn turn restores identical words', async () => { + const services = createTurnServices({ readiness: 'pending' }); + const view = setup({ chat: { conversation, text: 'Send now.' }, services }); + await waitFor(() => expect(screen.getByTestId('composer-send-button')).toBeEnabled()); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(view.streams).toHaveLength(1)); + act(() => + view.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('Send now.')); + services.readiness = 'ready'; + view.refresh(); await settle(); + expect(view.store.get(sideChatAtom)?.text).toBeUndefined(); expect(view.sendMessages).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue('Send now.'); + }); + + it('leaves a rejected manual handoff armed until automatic admission becomes ready', async () => { + let allowed = false; + const services = createTurnServices({ readiness: 'pending', canSubmit: () => allowed }); + const view = setup({ chat: { conversation, text: 'Wait for me.' }, services }); + await waitFor(() => expect(screen.getByTestId('composer-send-button')).toBeEnabled()); + fireEvent.click(screen.getByTestId('composer-send-button')); + expect(view.store.get(sideChatAtom)?.text).toBe('Wait for me.'); + expect(view.onHandedTextTaken).not.toHaveBeenCalled(); + expect(view.sendMessages).not.toHaveBeenCalled(); + allowed = true; + services.readiness = 'ready'; + view.refresh(); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + expect(view.store.get(sideChatAtom)?.text).toBeUndefined(); expect(field()).toHaveValue(''); }); + it('does not automatically send an equal pre-existing draft', async () => { + const view = setup({ chat: { conversation, text: 'My question.' }, draft: 'My question.' }); + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(view.store.get(sideChatAtom)?.text).toBeUndefined(); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(field()).toHaveValue('My question.'); + }); + + it('does not clear different side words written during the synchronous promotion handoff', async () => { + const view = setup({ draft: 'Transfer these words.' }); + await waitFor(() => expect(rows()).toHaveLength(2)); + view.handOffComposerText.mockImplementation(() => + view.store.set(sideChatDraftFamily(conversationId), 'New side words.'), + ); + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + expect(view.handOffComposerText).toHaveBeenCalledWith(conversationId, 'Transfer these words.'); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe('New side words.'); + }); + it('does not submit a pending handoff after the panel closes', async () => { const services = createTurnServices({ readiness: 'pending' }); const view = setup({ chat: { conversation, text: 'Carry on from here.' }, services }); @@ -547,13 +626,15 @@ describe('SideChatPanel', () => { }); it('moves the conversation into the main chat’s place, or closes', async () => { - const { openConversation, onClose } = setup(); + const { openConversation, onClose, open } = 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); + open({ conversation }); + await waitFor(() => expect(rows()).toHaveLength(2)); fireEvent.click(screen.getByRole('button', { name: 'Close' })); expect(onClose).toHaveBeenCalledTimes(2); }); diff --git a/packages/chat/src/components/side/panel.tsx b/packages/chat/src/components/side/panel.tsx index dcba995d9a4..eda67e638b1 100644 --- a/packages/chat/src/components/side/panel.tsx +++ b/packages/chat/src/components/side/panel.tsx @@ -93,16 +93,19 @@ function SideChatComposer({ onHandedTextTaken(); }, [ask, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue, value]); - /** Editing is a new intent: a delayed handoff must not send or restore older words. */ + /** Editing or an accepted manual send supersedes automatic intent, including after rollback. */ + const consume = useCallback(() => { + if (handedText && handed.current !== conversationId) { + handed.current = conversationId; + onHandedTextTaken(); + } + }, [conversationId, handedText, onHandedTextTaken]); const change = useCallback( (text: string) => { - if (handedText && handed.current !== conversationId) { - handed.current = conversationId; - onHandedTextTaken(); - } + consume(); setValue(text); }, - [conversationId, handedText, onHandedTextTaken, setValue], + [consume, setValue], ); const submit = useCallback(() => { @@ -110,8 +113,9 @@ function SideChatComposer({ if (text === '' || ask({ text }) === false) { return; } + consume(); setValue(''); - }, [ask, setValue, value]); + }, [ask, consume, setValue, value]); /** The main chat form's own Enter decision table, so a rebound submit shortcut holds here. */ const resolveKeyVerdict = useCallback( @@ -231,6 +235,7 @@ export default function SideChatPanel({ /** Words not sent yet go with the conversation, to the composer it opens under. */ if (draft.trim() !== '') { handOffComposerText(conversationId, draft); + setDraft((current) => (current === draft ? '' : current)); } openConversation(pane.conversation ?? opened); onClose(); @@ -242,6 +247,7 @@ export default function SideChatPanel({ openConversation, opened, pane.conversation, + setDraft, ]); let body: ReactNode; diff --git a/packages/chat/src/react/chat/__tests__/driven.spec.tsx b/packages/chat/src/react/chat/__tests__/driven.spec.tsx index 7591c356319..04f083d70aa 100644 --- a/packages/chat/src/react/chat/__tests__/driven.spec.tsx +++ b/packages/chat/src/react/chat/__tests__/driven.spec.tsx @@ -7,6 +7,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { Constants, + QueryKeys, StepTypes, StepEvents, ContentTypes, @@ -225,7 +226,7 @@ function setup({ { wrapper, initialProps: { live: false } }, ); const ready = () => waitFor(() => expect(view.result.current.followed.isLoading).toBe(false)); - return { ...view, ...harness, store, services, loadMessages, onWithdrawn, ready }; + return { ...view, ...harness, queryClient, store, services, loadMessages, onWithdrawn, ready }; } describe('useDrivenContract', () => { @@ -674,6 +675,43 @@ describe('useDrivenContract', () => { ]); }); + it('does not restore a withdrawn turn after cleanup during its real reconciliation write', async () => { + const view = setup(); + await view.ready(); + act(() => view.result.current.contract.ask({ text: 'Do not restore after leaving.' })); + await waitFor(() => expect(view.streams).toHaveLength(1)); + let cleaned = false; + const unsubscribe = view.queryClient.getQueryCache().subscribe((event) => { + if ( + event.type !== 'updated' || + event.query.queryKey[0] !== QueryKeys.messages || + event.query.queryKey[1] !== conversationId + ) + return; + const messages = event.query.state.data as TMessage[] | undefined; + if (!cleaned && ids(messages).join(',') === 'user-1,response-1') { + cleaned = true; + view.unmount(); + } + }); + act(() => + view.streams[0].push({ + type: 'final', + data: { + final: true, + earlyAbort: true, + conversation: { conversationId }, + requestMessage: null, + responseMessage: null, + }, + } as unknown as ChatEvent), + ); + await waitFor(() => expect(cleaned).toBe(true)); + await settle(); + unsubscribe(); + expect(view.onWithdrawn).not.toHaveBeenCalled(); + }); + it('takes back a turn stopped before the server kept anything of it', async () => { const { result, sendMessages, streams, onWithdrawn, loadMessages, ready } = setup(); await ready(); diff --git a/packages/chat/src/react/follow.ts b/packages/chat/src/react/follow.ts index 635df9e1a9b..cd25e19ac22 100644 --- a/packages/chat/src/react/follow.ts +++ b/packages/chat/src/react/follow.ts @@ -583,7 +583,7 @@ export function useFollowChat({ if (completed != null) { await chat.setMessages(completed); } - if (current.withdrawn === true) { + if (!stale && current.withdrawn === true) { host.current.onWithdrawn?.(turn); } /** diff --git a/packages/chat/src/react/side/__tests__/state.spec.ts b/packages/chat/src/react/side/__tests__/state.spec.ts index e0798439b94..a2649bfe00c 100644 --- a/packages/chat/src/react/side/__tests__/state.spec.ts +++ b/packages/chat/src/react/side/__tests__/state.spec.ts @@ -61,3 +61,44 @@ it('does not seed a shared empty-id draft for an invalid destination', () => { }); expect(store.get(sideChatDraftFamily(''))).toBe(''); }); + +it.each(['Same words.', 'Different draft.'])( + 'suppresses new handoff intent whenever an existing draft wins: %s', + (draft) => { + const store = createStore(); + store.set(sideChatDraftFamily('destination'), draft); + store.set(sideChatAtom, { conversation, text: 'Same words.' }); + expect(store.get(sideChatDraftFamily('destination'))).toBe(draft); + expect(store.get(sideChatAtom)?.text).toBeUndefined(); + }, +); + +it('distinguishes same-ID/text functional refinement from a genuine new direct opening', () => { + const store = createStore(); + store.set(sideChatAtom, { conversation, text: 'My question.' }); + store.set( + sideChatAtom, + (current) => + current && { ...current, conversation: { ...current.conversation, title: 'Loaded' } }, + ); + expect(store.get(sideChatAtom)?.text).toBe('My question.'); + const current = store.get(sideChatAtom); + store.set(sideChatAtom, current); + expect(store.get(sideChatAtom)).toBe(current); + store.set(sideChatAtom, { conversation, text: 'My question.' }); + expect(store.get(sideChatDraftFamily('destination'))).toBe('My question.'); + expect(store.get(sideChatAtom)?.text).toBeUndefined(); +}); + +it('normalizes a functional destination change while preserving both drafts', () => { + const store = createStore(); + store.set(sideChatDraftFamily('other'), 'Owned draft.'); + store.set(sideChatAtom, { conversation, text: 'Original.' }); + store.set(sideChatAtom, () => ({ + conversation: { ...conversation, conversationId: 'other' }, + text: 'Owned draft.', + })); + expect(store.get(sideChatDraftFamily('destination'))).toBe('Original.'); + expect(store.get(sideChatDraftFamily('other'))).toBe('Owned draft.'); + expect(store.get(sideChatAtom)?.text).toBeUndefined(); +}); diff --git a/packages/chat/src/react/side/state.ts b/packages/chat/src/react/side/state.ts index 8302124a45d..7260034e6ca 100644 --- a/packages/chat/src/react/side/state.ts +++ b/packages/chat/src/react/side/state.ts @@ -62,22 +62,30 @@ export const sideChatAtom: WritableAtom get(shownSideChatAtom), (get, set, next: SetStateAction) => { const current = get(shownSideChatAtom); - const value = typeof next === 'function' ? next(current) : next; + const refinement = typeof next === 'function'; + let value = refinement ? next(current) : next; /** A change of what is shown, not a refinement of it, is the reader's newest choice. */ if (value?.conversation.conversationId !== current?.conversation.conversationId) { set(sideChatRequestAtom, null); } const id = value?.conversation.conversationId; const text = value?.text; - /** Keep the words before a pane or its history loads. A refinement cannot resurrect - * an intent the reader has already edited or cleared. Existing drafts take precedence. */ + /** Direct opens grant new intent; functional refinements preserve an existing one. + * Only a handoff that seeds an empty draft may automatically send it. */ if ( + value != null && id && text && - (id !== current?.conversation.conversationId || text !== current?.text) && - get(sideChatDraftFamily(id)) === '' + ((!refinement && value !== current) || + id !== current?.conversation.conversationId || + text !== current?.text) ) { - set(sideChatDraftFamily(id), text); + const draft = sideChatDraftFamily(id); + if (get(draft) === '') { + set(draft, text); + } else { + value = { conversation: value.conversation }; + } } set(shownSideChatAtom, value); }, From 5cf90ad678000330ad8099357d40c1b4474fa8b5 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:44:19 -0800 Subject: [PATCH 4/7] Preserve Pending Side Chat Admission and Withdrawn Drafts --- e2e/specs/mock/subagent-activity.spec.ts | 89 ++++++++++ .../components/side/__tests__/panel.spec.tsx | 160 ++++++++++++++++++ packages/chat/src/components/side/panel.tsx | 12 +- .../chat/src/core/code/__fixtures__/turn.ts | 103 +++++++++++ .../chat/src/core/code/__tests__/turn.spec.ts | 143 ++++++---------- packages/chat/src/core/code/index.ts | 3 +- packages/chat/src/core/code/turn.ts | 61 +++++-- packages/chat/src/core/code/workspace.ts | 3 + .../chat/src/react/__tests__/follow.spec.tsx | 64 +++++++ .../src/react/chat/__tests__/driven.spec.tsx | 27 ++- packages/chat/src/react/chat/driven.ts | 18 +- packages/chat/src/react/chat/turns.ts | 67 +++++--- packages/chat/src/react/follow.ts | 37 +++- 13 files changed, 628 insertions(+), 159 deletions(-) create mode 100644 packages/chat/src/core/code/__fixtures__/turn.ts diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index 9f024fe0cf0..989fe8c9186 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -21,6 +21,7 @@ import { } from './agents.helpers'; import history from '../../fixtures/subagent-history.cjs'; import { openChatHistory } from './scenarios/sidebar'; +import { installCodeMocks, singleMachine } from './scenarios/codeWorkspaceMocks'; const DETACHED_ACTIVITY_MARKER = 'E2E_SUBAGENT_ACTIVITY:'; /** Long enough for a stream that was going to reattach on its own to have done so. */ @@ -349,12 +350,23 @@ test.describe('detached subagent activity', () => { 'switch', 'refetch-success', 'refetch-denial', + 'workspace', ] as const) { test(`continues a finished child and preserves pending words on ${action} @scenario:subagent-continue-opens-side-chat-${action}`, async ({ page, }) => { test.setTimeout(120_000); const label = `beside-${Date.now().toString(36)}`; + const workspace = action === 'workspace'; + let releaseWorkspace: () => void = () => undefined; + const workspaceReady = new Promise((resolve) => { + releaseWorkspace = resolve; + }); + let sawWorkspace: () => void = () => undefined; + const workspaceRequested = new Promise((resolve) => { + sawWorkspace = resolve; + }); + let workspaceConversation = ''; const refetch = action === 'refetch-success' || action === 'refetch-denial'; const promote = action === 'promote' || action === 'promote-clear'; /** The fixture's parent dispatches exactly two children; the first is the one continued. */ @@ -415,6 +427,21 @@ test.describe('detached subagent activity', () => { return; } observedAgent(); + if (workspace) { + const response = await route.fetch(); + const body = await response.json(); + await route.fulfill({ + response, + json: { + ...body, + tools: ['execute_code'], + stateful_code_sessions: true, + code_environment_id: 'env-zimacube', + code_workspace_id: 'librechat', + }, + }); + return; + } await agentReady; if (action === 'refetch-denial') { await route.fulfill({ status: 403, json: { message: 'Agent access denied.' } }); @@ -432,6 +459,53 @@ test.describe('detached subagent activity', () => { /** The path, not the whole address: the app drops the agent query once the turn is in. */ const parentPath = new URL(page.url()).pathname; + if (workspace) { + /** Reuse the paired-worker boundary fixture. Reload only setup configuration, before + * opening the handoff; no refresh or navigation is used to wake its pending attempt. */ + await installCodeMocks(page, { environments: [singleMachine()] }); + await page.route('**/api/code-environments/env-zimacube/status', async (route) => { + sawWorkspace(); + await workspaceReady; + await route.fallback(); + }); + await page.route('**/api/convos/fork*', async (route) => { + const response = await route.fetch(); + const body = await response.json(); + expect(body.conversation).toBeTruthy(); + workspaceConversation = body.conversation.conversationId; + await route.fulfill({ + response, + json: { + ...body, + conversation: { + ...body.conversation, + codeEnvironmentMode: 'attached', + codeWorkspaces: [{ environmentId: 'env-zimacube', workspaceId: 'librechat' }], + }, + }, + }); + }); + await page.route(/\/api\/agents\/chat\/[^/?]+(?:\?.*)?$/, async (route) => { + const request = route.request(); + if ( + request.method() !== 'POST' || + !workspaceConversation || + request.postDataJSON()?.conversationId !== workspaceConversation + ) { + await route.continue(); + return; + } + const body = request.postDataJSON(); + expect(body.codeEnvironmentMode).toBe('attached'); + expect(body.codeWorkspaces).toEqual([ + { environmentId: 'env-zimacube', workspaceId: 'librechat' }, + ]); + /** This fixture proves client admission and its single HTTP submission, not code-worker execution. */ + await route.fulfill({ status: 200, json: { conversationId: workspaceConversation } }); + }); + await page.reload(); + } + 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 }); @@ -465,6 +539,20 @@ test.describe('detached subagent activity', () => { await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue( 'What did you find?', ); + if (workspace) { + /** Only the coding destination's resolved details cause this first status query. */ + await workspaceRequested; + expect(starts.slice(startsBefore)).toEqual([]); + await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue( + 'What did you find?', + ); + releaseWorkspace(); + await expect.poll(() => starts.slice(startsBefore)).toEqual([sideConversationId]); + await expect(sideChat.getByRole('textbox', { name: 'Message input' })).toHaveValue(''); + await expect(sideChat.getByRole('button', { name: 'Stop generating' })).toHaveCount(0); + expect(starts.slice(startsBefore)).toEqual([sideConversationId]); + return; + } if (action === 'refetch-denial') { const denied = page.waitForResponse( (response) => new URL(response.url()).pathname === `/api/agents/${children[0].id}`, @@ -576,6 +664,7 @@ test.describe('detached subagent activity', () => { await expect(main).toContainText('And then?'); } finally { releaseAgent(); + releaseWorkspace(); for (const agentId of createdAgentIds.reverse()) { await cleanupAgent(page, agentId); } diff --git a/packages/chat/src/components/side/__tests__/panel.spec.tsx b/packages/chat/src/components/side/__tests__/panel.spec.tsx index 5ce57238e23..ff49bceaaad 100644 --- a/packages/chat/src/components/side/__tests__/panel.spec.tsx +++ b/packages/chat/src/components/side/__tests__/panel.spec.tsx @@ -16,6 +16,7 @@ import { sideChatAtom, sideChatDraftFamily } from '../../../react/side/state'; import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; import { ChatSurfaceProvider } from '../../../react/subagents/provider'; import { createMessagesHost } from '../../../__fixtures__/messagesHost'; +import { turnInputs } from '../../../core/code/__fixtures__/turn'; import { SideChatHostProvider } from '../../../react/side/host'; import { MessagePartsHostProvider } from '../../../react/host'; import { ChatHostProvider } from '../../../react/chat/host'; @@ -234,6 +235,7 @@ function setup({ return { ...view, store, + queryClient, open: (next: SideChat) => act(() => store.set(sideChatAtom, next)), refresh: () => view.rerender(tree()), /** Draws the panel again from nothing, as the layout does when it moves it. */ @@ -597,6 +599,164 @@ describe('SideChatPanel', () => { expect(view.store.get(sideChatDraftFamily(conversationId))).toBe('New side words.'); }); + it.each(['attached', 'legacy', 'recovery', 'replacement'] as const)( + 'preserves automatic intent through real %s workspace admission', + async (mode) => { + const inputs = turnInputs(); + if (mode === 'legacy') inputs.workspace.startupConfig = {}; + if (mode === 'recovery') inputs.workspace.recoveryPending = true; + else if (mode === 'replacement') inputs.workspace.replacingDecision = true; + else inputs.workspace.statuses['personal-vm'] = { isLoading: true, isError: false }; + const services = createTurnServices({ readCodeInputs: () => inputs }); + const selected = { ...conversation, ...inputs.workspace.conversation!, conversationId }; + inputs.workspace.conversation = selected; + inputs.approval.conversation = selected; + const view = setup({ + chat: { conversation: selected, text: 'Use the workspace.' }, + services, + }); + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(view.sendMessages).not.toHaveBeenCalled(); + expect(view.store.get(sideChatAtom)?.text).toBe('Use the workspace.'); + view.refresh(); + view.refresh(); + expect(services.logger.warn).not.toHaveBeenCalled(); + inputs.workspace.recoveryPending = false; + inputs.workspace.replacingDecision = false; + inputs.workspace.statuses = turnInputs().workspace.statuses; + view.refresh(); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + view.refresh(); + await settle(); + expect(view.sendMessages).toHaveBeenCalledTimes(1); + expect(field()).toHaveValue(''); + }, + ); + + it('keeps terminal workspace refusal manual without retrying on unrelated renders', async () => { + const inputs = turnInputs(); + inputs.workspace.statuses['personal-vm'] = { isLoading: false, isError: true }; + const view = setup({ + chat: { conversation, text: 'Unavailable workspace.' }, + services: createTurnServices({ readCodeInputs: () => inputs }), + }); + await waitFor(() => expect(rows()).toHaveLength(2)); + expect(view.store.get(sideChatAtom)?.text).toBeUndefined(); + expect(field()).toHaveValue('Unavailable workspace.'); + inputs.workspace.statuses = turnInputs().workspace.statuses; + view.refresh(); + await settle(); + expect(view.sendMessages).not.toHaveBeenCalled(); + }); + + it('sends an explicit without-attached decision without waiting for unrelated workspace status', async () => { + const inputs = turnInputs(); + inputs.workspace.conversation = { + ...inputs.workspace.conversation!, + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }; + inputs.workspace.statuses['personal-vm'] = { isLoading: true, isError: false }; + const view = setup({ + chat: { + conversation: { ...conversation, codeEnvironmentMode: 'without_attached' }, + text: 'No attached workspace.', + }, + services: createTurnServices({ readCodeInputs: () => inputs }), + }); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + expect(field()).toHaveValue(''); + }); + + it.each(['close', 'remount'] as const)( + 'preserves known withdrawn words through %s during reconciliation', + async (action) => { + const view = setup(); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'Keep withdrawn words.' } }); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(view.streams).toHaveLength(1)); + let cleaned = false; + const unsubscribe = view.queryClient.getQueryCache().subscribe((event) => { + if ( + event.type !== 'updated' || + event.query.queryKey[0] !== 'messages' || + event.query.queryKey[1] !== conversationId + ) + return; + const messages = event.query.state.data as TMessage[] | undefined; + if (!cleaned && messages?.length === 2) { + cleaned = true; + if (action === 'close') view.store.set(sideChatAtom, null); + view.unmount(); + } + }); + act(() => + view.streams[0].push({ + type: 'final', + data: { + final: true, + earlyAbort: true, + conversation: { conversationId }, + requestMessage: null, + responseMessage: null, + }, + } as unknown as ChatEvent), + ); + await waitFor(() => expect(cleaned).toBe(true)); + await settle(); + unsubscribe(); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe('Keep withdrawn words.'); + if (action === 'close') view.open({ conversation }); + view.remount(); + await waitFor(() => expect(field()).toHaveValue('Keep withdrawn words.')); + expect(view.sendMessages).toHaveBeenCalledTimes(1); + }, + ); + + it('restitutes known withdrawal before stop acknowledgement so promotion transfers exactly one copy', async () => { + const view = setup(); + let acknowledge!: () => void; + view.abort.mockImplementation( + () => + new Promise((resolve) => { + acknowledge = () => resolve({ success: true }); + }), + ); + await waitFor(() => expect(rows()).toHaveLength(2)); + fireEvent.change(field(), { target: { value: 'Move the withdrawn words.' } }); + fireEvent.click(screen.getByTestId('composer-send-button')); + await waitFor(() => expect(view.streams).toHaveLength(1)); + fireEvent.click(await screen.findByRole('button', { name: 'Stop generating' })); + await waitFor(() => expect(view.abort).toHaveBeenCalledTimes(1)); + act(() => + view.streams[0].push({ + type: 'final', + data: { + final: true, + earlyAbort: true, + conversation: { conversationId }, + requestMessage: null, + responseMessage: null, + }, + } as unknown as ChatEvent), + ); + try { + await waitFor(() => expect(field()).toHaveValue('Move the withdrawn words.')); + fireEvent.click(screen.getByRole('button', { name: 'Open as the main chat' })); + expect(view.handOffComposerText).toHaveBeenCalledTimes(1); + expect(view.handOffComposerText).toHaveBeenCalledWith( + conversationId, + 'Move the withdrawn words.', + ); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe(''); + } finally { + await act(async () => acknowledge()); + } + await settle(); + expect(view.store.get(sideChatDraftFamily(conversationId))).toBe(''); + }); + it('does not submit a pending handoff after the panel closes', async () => { const services = createTurnServices({ readiness: 'pending' }); const view = setup({ chat: { conversation, text: 'Carry on from here.' }, services }); diff --git a/packages/chat/src/components/side/panel.tsx b/packages/chat/src/components/side/panel.tsx index eda67e638b1..061c822c032 100644 --- a/packages/chat/src/components/side/panel.tsx +++ b/packages/chat/src/components/side/panel.tsx @@ -4,6 +4,7 @@ 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 { useDrivenContract } from '../../react/chat/driven'; import type { ChatContract } from '../../react/chat/contract'; import type { TurnReadiness } from '../../react/chat/host'; import type { SideChat } from '../../react/side/state'; @@ -17,6 +18,7 @@ import DrivenThread from '../pane/Driven'; type SideChatComposerProps = { contract: ChatContract; + attempt: ReturnType['attempt']; readiness: TurnReadiness; /** The reader's unsent words, which the panel holds so they outlive the composer. */ value: string; @@ -43,6 +45,7 @@ type SideChatComposerProps = { */ function SideChatComposer({ contract, + attempt, readiness, value, onChange: setValue, @@ -86,12 +89,12 @@ function SideChatComposer({ ) { return; } + const outcome = value === handedText && readiness === 'ready' ? attempt(handedText) : 'blocked'; + if (outcome === 'pending') return; handed.current = conversationId; - if (value === handedText && readiness === 'ready' && ask({ text: handedText }) !== false) { - setValue(''); - } + if (outcome === 'accepted') setValue(''); onHandedTextTaken(); - }, [ask, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue, value]); + }, [attempt, conversationId, handedText, onHandedTextTaken, readiness, ready, setValue, value]); /** Editing or an accepted manual send supersedes automatic intent, including after rollback. */ const consume = useCallback(() => { @@ -284,6 +287,7 @@ export default function SideChatPanel({ {(contract) => ( = {}): TConversation => ({ + conversationId: 'new', + title: 'Code', + endpoint: EModelEndpoint.agents, + agent_id: 'agent_primary', + createdAt: '2026-09-01T00:00:00.000Z', + updatedAt: '2026-09-01T00:00:00.000Z', + ...overrides, +}); + +export const statefulCodeSessions: NonNullable = { + allowedEnvironments: ['user'], + approvalsEnabled: true, + approvalModes: ['ask', 'acceptEdits'], + environments: [ + { + id: 'personal-vm', + name: 'Personal VM', + type: 'attached', + configSchema: { + permissions: { + fileWrite: { allowed: ['ask', 'allow'], default: 'ask' }, + commandExecution: { allowed: ['ask'], default: 'ask' }, + }, + }, + }, + ], +}; + +export const projectA: CodeWorkspaceSelection = { + environmentId: 'personal-vm', + workspaceId: 'project-a', +}; +export const projectB: CodeWorkspaceSelection = { + environmentId: 'personal-vm', + workspaceId: 'project-b', +}; + +/** An agents chat that requires a workspace, with two ready and the first chosen. */ +export const turnInputs = (overrides: Partial = {}): TurnCodeInputs => ({ + workspace: { + conversation: conversation({ codeEnvironmentMode: 'attached', codeWorkspaces: [projectA] }), + primaryAgent: agent, + agentsMap: {}, + statefulCodeSessions, + startupConfig: { codeEnvironmentDecisionVersion: CODE_ENVIRONMENT_DECISION_VERSION }, + canRunCode: true, + capabilities: ['execute_code', 'stateful_code_sessions'], + configurationLoaded: true, + recoveryPending: false, + replacingDecision: false, + statuses: { + 'personal-vm': { + data: { + environmentId: 'personal-vm', + status: 'ready', + workspaces: [{ id: 'project-a' }, { id: 'project-b' }], + }, + isLoading: false, + isError: false, + }, + }, + getPreferredWorkspace: () => undefined, + }, + approval: { + conversation: conversation({ conversationId: 'conversation-1' }), + statefulCodeSessions, + reachable: { agents: [agent], complete: true }, + }, + latest: null, + ...overrides, +}); diff --git a/packages/chat/src/core/code/__tests__/turn.spec.ts b/packages/chat/src/core/code/__tests__/turn.spec.ts index 05dc7ea6da8..1b239498ab3 100644 --- a/packages/chat/src/core/code/__tests__/turn.spec.ts +++ b/packages/chat/src/core/code/__tests__/turn.spec.ts @@ -1,103 +1,56 @@ -import { Tools, EModelEndpoint, CODE_ENVIRONMENT_DECISION_VERSION } from 'librechat-data-provider'; -import type { - Agent, - TConfig, - TConversation, - CodeWorkspaceSelection, -} from 'librechat-data-provider'; -import type { TurnCodeInputs } from '../turn'; -import { resolveTurnCode } from '../turn'; +import { agent, conversation, projectA, projectB, turnInputs } from '../__fixtures__/turn'; +import { resolveTurnCode, resolveTurnCodeResult } from '../turn'; +import * as workspace from '../workspace'; -const agent: Agent = { - id: 'agent_primary', - name: null, - description: null, - created_at: 0, - avatar: null, - provider: EModelEndpoint.openAI, - model: null, - model_parameters: { - temperature: null, - maxContextTokens: null, - max_context_tokens: null, - max_output_tokens: null, - top_p: null, - frequency_penalty: null, - presence_penalty: null, - }, - stateful_code_sessions: true, - tools: [Tools.execute_code], - code_environment_id: 'personal-vm', -}; - -const conversation = (overrides: Partial = {}): TConversation => ({ - conversationId: 'new', - title: 'Code', - endpoint: EModelEndpoint.agents, - agent_id: 'agent_primary', - createdAt: '2026-09-01T00:00:00.000Z', - updatedAt: '2026-09-01T00:00:00.000Z', - ...overrides, -}); +describe('resolveTurnCode', () => { + it('admits a sealed without-attached decision before irrelevant linked metadata loads', () => { + const inputs = turnInputs(); + inputs.workspace.primaryAgent = { ...agent, agent_ids: ['agent_child'] }; + inputs.workspace.agentsMap = undefined; + const selected = conversation({ + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }); + inputs.workspace.conversation = selected; + expect(resolveTurnCodeResult(inputs, selected).state).toBe('ready'); + }); -const statefulCodeSessions: NonNullable = { - allowedEnvironments: ['user'], - approvalsEnabled: true, - approvalModes: ['ask', 'acceptEdits'], - environments: [ - { - id: 'personal-vm', - name: 'Personal VM', - type: 'attached', - configSchema: { - permissions: { - fileWrite: { allowed: ['ask', 'allow'], default: 'ask' }, - commandExecution: { allowed: ['ask'], default: 'ask' }, - }, - }, - }, - ], -}; + it('keeps an unsupported legacy without-attached decision terminal while other data loads', () => { + const inputs = turnInputs(); + inputs.workspace.startupConfig = {}; + inputs.workspace.statuses['personal-vm'] = { isLoading: true, isError: false }; + const selected = conversation({ + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }); + inputs.workspace.conversation = selected; + expect(resolveTurnCodeResult(inputs, selected).state).toBe('blocked'); + }); -const projectA: CodeWorkspaceSelection = { environmentId: 'personal-vm', workspaceId: 'project-a' }; -const projectB: CodeWorkspaceSelection = { environmentId: 'personal-vm', workspaceId: 'project-b' }; + it('distinguishes unknown linked metadata from a loaded missing target', () => { + const inputs = turnInputs(); + inputs.workspace.primaryAgent = { ...agent, agent_ids: ['agent_child'] }; + inputs.workspace.agentsMap = undefined; + expect(resolveTurnCodeResult(inputs, inputs.workspace.conversation).state).toBe('pending'); + inputs.workspace.agentsMap = {}; + expect(resolveTurnCodeResult(inputs, inputs.workspace.conversation).state).toBe('blocked'); + }); -/** An agents chat that requires a workspace, with two ready and the first chosen. */ -const turnInputs = (overrides: Partial = {}): TurnCodeInputs => ({ - workspace: { - conversation: conversation({ codeEnvironmentMode: 'attached', codeWorkspaces: [projectA] }), - primaryAgent: agent, - agentsMap: {}, - statefulCodeSessions, - startupConfig: { codeEnvironmentDecisionVersion: CODE_ENVIRONMENT_DECISION_VERSION }, - canRunCode: true, - capabilities: ['execute_code', 'stateful_code_sessions'], - configurationLoaded: true, - recoveryPending: false, - replacingDecision: false, - statuses: { - 'personal-vm': { - data: { - environmentId: 'personal-vm', - status: 'ready', - workspaces: [{ id: 'project-a' }, { id: 'project-b' }], - }, - isLoading: false, - isError: false, - }, - }, - getPreferredWorkspace: () => undefined, - }, - approval: { - conversation: conversation({ conversationId: 'conversation-1' }), - statefulCodeSessions, - reachable: { agents: [agent], complete: true }, - }, - latest: null, - ...overrides, -}); + it('derives workspace once for a reason-preserving attempt and once for the manual wrapper', () => { + const derive = jest.spyOn(workspace, 'resolveCodeWorkspace'); + try { + const inputs = turnInputs(); + const selected = inputs.workspace.conversation; + expect(resolveTurnCodeResult(inputs, selected).state).toBe('ready'); + expect(derive).toHaveBeenCalledTimes(1); + derive.mockClear(); + expect(resolveTurnCode(inputs, selected)).not.toBeNull(); + expect(derive).toHaveBeenCalledTimes(1); + } finally { + derive.mockRestore(); + } + }); -describe('resolveTurnCode', () => { it('waits while a recovery is pending', () => { const inputs = turnInputs(); expect( diff --git a/packages/chat/src/core/code/index.ts b/packages/chat/src/core/code/index.ts index 86e7e54a301..81b022f318b 100644 --- a/packages/chat/src/core/code/index.ts +++ b/packages/chat/src/core/code/index.ts @@ -1,4 +1,5 @@ export * from './routing'; export * from './approval'; export * from './workspace'; -export * from './turn'; +export { resolveTurnCode } from './turn'; +export type { TurnCodeInputs, TurnCodeDecision } from './turn'; diff --git a/packages/chat/src/core/code/turn.ts b/packages/chat/src/core/code/turn.ts index 601efe445bd..ecb24e572fd 100644 --- a/packages/chat/src/core/code/turn.ts +++ b/packages/chat/src/core/code/turn.ts @@ -22,14 +22,15 @@ export interface TurnCodeDecision { apply: (conversation: TConversation) => TConversation | null; } -/** - * The code decision for one send, or `null` when the send has to wait: a recovery or replacement - * is in flight, or the attached workspaces cannot be resolved yet. - */ -export function resolveTurnCode( +export type TurnCodeResult = + | { state: 'ready'; decision: TurnCodeDecision } + | { state: 'pending' | 'blocked' }; + +/** The same single workspace derivation used by both manual and automatic admission. */ +export function resolveTurnCodeResult( { workspace, approval, latest }: TurnCodeInputs, submitted: TConversation | null, -): TurnCodeDecision | null { +): TurnCodeResult { const derivation = resolveCodeWorkspace(workspace); const latestApprovalMode = latest?.codeApprovalMode; const submission = derivation.resolveSubmission( @@ -37,7 +38,19 @@ export function resolveTurnCode( latest?.codeEnvironmentMode ?? submitted?.codeEnvironmentMode, ); if (submission == null) { - return null; + const requestedMode = latest?.codeEnvironmentMode ?? submitted?.codeEnvironmentMode; + if (requestedMode === 'without_attached' && !derivation.supportsEnvironmentDecisions) { + return { state: 'blocked' }; + } + if (workspace.recoveryPending || workspace.replacingDecision) return { state: 'pending' }; + const terminal = derivation.environments.some( + ({ state }) => state === 'unavailable' || state === 'unsupported' || state === 'missing', + ); + const loading = + derivation.metadataPending === true || + derivation.state === 'loading' || + Object.values(workspace.statuses).some((status) => status?.isLoading === true); + return { state: !terminal && loading ? 'pending' : 'blocked' }; } const { modes, selected } = resolveCodeApprovalModes({ ...approval, @@ -45,17 +58,29 @@ export function resolveTurnCode( }); const { codeEnvironmentMode, codeWorkspaces } = submission; return { - code: { - approvalMode: resolveSubmittedCodeApprovalMode({ - requested: latestApprovalMode, - modes, - fallback: selected, - codeEnvironmentMode, - }), - latestApprovalMode, - environmentMode: codeEnvironmentMode, - workspaces: codeWorkspaces, + state: 'ready', + decision: { + code: { + approvalMode: resolveSubmittedCodeApprovalMode({ + requested: latestApprovalMode, + modes, + fallback: selected, + codeEnvironmentMode, + }), + latestApprovalMode, + environmentMode: codeEnvironmentMode, + workspaces: codeWorkspaces, + }, + apply: (current) => withSubmittedCodeDecision(current, submission), }, - apply: (current) => withSubmittedCodeDecision(current, submission), }; } + +/** A manual send's code decision, retaining the established null refusal contract. */ +export function resolveTurnCode( + inputs: TurnCodeInputs, + submitted: TConversation | null, +): TurnCodeDecision | null { + const result = resolveTurnCodeResult(inputs, submitted); + return result.state === 'ready' ? result.decision : null; +} diff --git a/packages/chat/src/core/code/workspace.ts b/packages/chat/src/core/code/workspace.ts index 2528b574fd4..1500ddef944 100644 --- a/packages/chat/src/core/code/workspace.ts +++ b/packages/chat/src/core/code/workspace.ts @@ -199,6 +199,8 @@ export interface CodeWorkspaceDerivation { mode?: CodeEnvironmentMode; state: CodeWorkspaceState; canSubmit: boolean; + /** A linked-agent catalog is still unknown, rather than loaded with a missing target. */ + metadataPending?: boolean; visible: boolean; environments: CodeWorkspaceEnvironmentResult[]; machineOptions?: TPublicCodeEnvironment[]; @@ -1019,6 +1021,7 @@ export function resolveCodeWorkspace(inputs: CodeWorkspaceInputs): CodeWorkspace mode: inferredMode, state: status.state, canSubmit, + metadataPending: !reachable.complete && agentsMap == null, visible: status.visible, environments: environments.environmentResults, machineOptions: environments.machineOptions, diff --git a/packages/chat/src/react/__tests__/follow.spec.tsx b/packages/chat/src/react/__tests__/follow.spec.tsx index 3cf5806d189..28e70413fce 100644 --- a/packages/chat/src/react/__tests__/follow.spec.tsx +++ b/packages/chat/src/react/__tests__/follow.spec.tsx @@ -160,6 +160,70 @@ const setup = (initial: Partial & Pick { + it.each([ + { outcome: 'joined', observed: true }, + { outcome: 'failed', observed: true }, + { outcome: 'joined', observed: false }, + { outcome: 'failed', observed: false }, + ] as const)( + 'publishes eligibility only on demand after a $outcome read (observed=$observed)', + async ({ outcome, observed }) => { + const { transport, streams, setStatus } = createTransport(running); + const stored = [brief, answer('Stored')]; + const loadMessages = jest.fn, []>(async () => stored); + const client = new QueryClient(); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const seen: boolean[] = []; + const view = renderHook( + (props: FollowChatOptions) => { + const followed = useFollowChat(props); + const eligible = observed ? followed.canSend() : true; + seen.push(eligible); + return { followed, eligible }; + }, + { wrapper, initialProps: { id: 'thread-1', transport, loadMessages, live: true } }, + ); + await waitFor(() => expect(streams).toHaveLength(1)); + setStatus(idle); + act(() => streams[0].push(final('Stored'))); + await waitFor(() => expect(view.result.current.followed.canSend()).toBe(true)); + await settle(); + if (outcome === 'joined') { + await act(async () => + view.result.current.followed.chat?.setMessages([ + { ...brief, messageId: 'older' }, + ...stored, + ]), + ); + } + const before = view.result.current.followed.messages; + let release!: (messages: TMessage[]) => void; + let reject!: (error: Error) => void; + loadMessages.mockImplementation( + () => + new Promise((resolve, fail) => { + release = resolve; + reject = fail; + }), + ); + view.rerender({ id: 'thread-1', transport, loadMessages, live: false }); + /** A real sender is refused while this read owns the list. No incidental render is needed. */ + if (observed) expect(view.result.current.followed.canSend()).toBe(false); + const renders = seen.length; + await act(async () => + outcome === 'joined' ? release(stored) : reject(new Error('read failed')), + ); + if (observed) await waitFor(() => expect(view.result.current.eligible).toBe(true)); + expect(view.result.current.followed.canSend()).toBe(true); + expect(view.result.current.followed.messages).toBe(before); + const transitions = seen.filter((value, index) => index === 0 || value !== seen[index - 1]); + expect(seen.length).toBe(renders + (observed ? 1 : 0)); + expect(transitions[transitions.length - 1]).toBe(true); + }, + ); + it('shows the stored messages and opens no stream when nothing is running', async () => { const { transport } = createTransport(idle); const { result, loadMessages, queryClient } = setup({ transport }); diff --git a/packages/chat/src/react/chat/__tests__/driven.spec.tsx b/packages/chat/src/react/chat/__tests__/driven.spec.tsx index 04f083d70aa..41100244ad0 100644 --- a/packages/chat/src/react/chat/__tests__/driven.spec.tsx +++ b/packages/chat/src/react/chat/__tests__/driven.spec.tsx @@ -17,7 +17,7 @@ import type { TMessage, ChatEvent, TConversation } from 'librechat-data-provider import type { ChatStream, ChatTransport, ChatSendRequest, ChatStreamStatus } from '../../../core'; import type { ChatHost, TurnServices } from '../host'; import type { ExtendedFile } from '../../../core'; -import { createTurnServices } from '../__fixtures__/services'; +import { createTurnServices, createTurnCodeInputs } from '../__fixtures__/services'; import { showStopButtonByIndex } from '../../generation'; import { isSubmittingFamily } from '../../submission'; import { useDrivenContract } from '../driven'; @@ -230,6 +230,27 @@ function setup({ } describe('useDrivenContract', () => { + it('retains manual refusal diagnostics and false/accepted-undefined return values', async () => { + const inputs = createTurnCodeInputs({ recoveryPending: true }); + const services = createTurnServices({ readCodeInputs: () => inputs }); + const view = setup({ services }); + await view.ready(); + let result: false | void; + act(() => { + result = view.result.current.contract.ask({ text: 'Wait for recovery.' }); + }); + expect(result!).toBe(false); + expect(services.logger.warn).toHaveBeenCalledWith( + '[useTurns] Refusing to send without an available code workspace', + ); + inputs.workspace.recoveryPending = false; + act(() => { + result = view.result.current.contract.ask({ text: 'Now recovered.' }); + }); + expect(result!).toBeUndefined(); + await waitFor(() => expect(view.sendMessages).toHaveBeenCalledTimes(1)); + }); + it('sends the turn ask builds through the chat, and shows the generation it starts', async () => { const { result, sendMessages, streams, store, loadMessages, ready } = setup(); await ready(); @@ -675,7 +696,7 @@ describe('useDrivenContract', () => { ]); }); - it('does not restore a withdrawn turn after cleanup during its real reconciliation write', async () => { + it('offers withdrawn words before cleanup during its real reconciliation write', async () => { const view = setup(); await view.ready(); act(() => view.result.current.contract.ask({ text: 'Do not restore after leaving.' })); @@ -709,7 +730,7 @@ describe('useDrivenContract', () => { await waitFor(() => expect(cleaned).toBe(true)); await settle(); unsubscribe(); - expect(view.onWithdrawn).not.toHaveBeenCalled(); + expect(view.onWithdrawn).toHaveBeenCalledTimes(1); }); it('takes back a turn stopped before the server kept anything of it', async () => { diff --git a/packages/chat/src/react/chat/driven.ts b/packages/chat/src/react/chat/driven.ts index 5acf5658b04..653378addb8 100644 --- a/packages/chat/src/react/chat/driven.ts +++ b/packages/chat/src/react/chat/driven.ts @@ -50,7 +50,10 @@ export function useDrivenContract({ followed, index, handoff = false, -}: DrivenContractOptions): ChatContract & { readiness: TurnReadiness } { +}: DrivenContractOptions): ChatContract & { + readiness: TurnReadiness; + attempt: ReturnType['attempt']; +} { const host = useChatHost(); const { chat, status, isLoading, isFollowing, canSend, send, stop } = followed; const [files, setFiles] = useAtom(filesFamily(index)); @@ -136,7 +139,10 @@ export function useDrivenContract({ ...appServices, canSubmit: (submitted) => canSend() && appServices.canSubmit?.(submitted) !== false, }; - const turns = useTurns(turnsParams, services); + const useReadiness = host.useTurnReadiness ?? useReady; + const readiness = useReadiness(conversation, handoff); + const turns = useTurns(turnsParams, services, () => (!canSend() ? 'pending' : readiness)); + const attempt = turns.attempt; const { ask, regenerate, handleRegenerate, handleContinue } = useTurnHandlers({ ask: turns.ask, regenerate: turns.regenerate, @@ -159,12 +165,13 @@ export function useDrivenContract({ const [optionSettings, setOptionSettings] = useAtom(optionSettingsFamily(index)); const feedbackEnabled = host.useFeedbackEnabled(); - const useReadiness = host.useTurnReadiness ?? useReady; - const readiness = useReadiness(conversation, handoff); - return useMemo( + return useMemo< + ChatContract & { readiness: TurnReadiness; attempt: ReturnType['attempt'] } + >( () => ({ index, readiness, + attempt, conversation, setConversation, newConversation, @@ -202,6 +209,7 @@ export function useDrivenContract({ id, index, readiness, + attempt, conversation, setConversation, newConversation, diff --git a/packages/chat/src/react/chat/turns.ts b/packages/chat/src/react/chat/turns.ts index 36d96118139..6092d7031cf 100644 --- a/packages/chat/src/react/chat/turns.ts +++ b/packages/chat/src/react/chat/turns.ts @@ -3,12 +3,11 @@ import { useStore, useSetAtom } from 'jotai'; import { useQueryClient } from '@tanstack/react-query'; import { Constants, EModelEndpoint, isAssistantsEndpoint } from 'librechat-data-provider'; import type { TMessage } from 'librechat-data-provider'; -import type { TAskFunction, TRegenerateFunction } from '../../core'; -import type { ChatTurnsParams, TurnServices } from './host'; +import type { TAskFunction, TAskProps, TOptions, TRegenerateFunction } from '../../core'; +import type { ChatTurnsParams, TurnServices, TurnReadiness } from './host'; import { buildTurn, resolveSender, - resolveTurnCode, createRegenerate, isSubmittableMessage, isInlineablePastedText, @@ -26,6 +25,7 @@ import { showStopButtonByIndex, launchedConversationFamily, } from '../generation'; +import { resolveTurnCodeResult } from '../../core/code/turn'; import { revealedQueuedTurnFamily } from '../steer/atoms'; import { siblingIdxFamily, siblingKey } from '../thread'; import { resolveSubmittedReasoning } from './reasoning'; @@ -33,6 +33,9 @@ import { activeUsageResponseIdFamily } from '../usage'; import { isSubmittingFamily } from '../submission'; import { isHistoryRevalidating } from './guards'; +type Attempt = 'accepted' | 'pending' | 'blocked'; +type Submit = (props: TAskProps, options?: TOptions, automatic?: boolean) => Attempt; + /** * Submits and regenerates turns for one pane: refuses a send the chat cannot take yet, drains * the composer's queued skills, quotes and reasoning, builds the turn and publishes it. The app @@ -53,7 +56,8 @@ export function useTurns( conversation: immutableConversation, }: ChatTurnsParams, services: TurnServices, -): { ask: TAskFunction; regenerate: TRegenerateFunction } { + admission?: () => TurnReadiness, +): { ask: TAskFunction; attempt: (text: string) => Attempt; regenerate: TRegenerateFunction } { const store = useStore(); const queryClient = useQueryClient(); const setIsSubmitting = useSetAtom(isSubmittingFamily(index)); @@ -107,7 +111,7 @@ export function useTurns( [store], ); - const ask: TAskFunction = ( + const submit: Submit = ( { text, overrideConvoId, @@ -135,6 +139,7 @@ export function useTurns( overrideExpectedPredecessorCreatedAt, overrideQueuedMessageOrigin, } = {}, + automatic = false, ) => { text = text.trim(); /** @@ -147,19 +152,21 @@ export function useTurns( /** A compaction sends no text: it replays the branch, like a regenerate, with the response * placeholder parented onto the leaf. */ const regenerateShaped = isRegenerate || compact; + /** An accepted or revealed local turn is newer explicit intent; it must not arm an + * automatic retry. Temporary transport/workspace phases below keep their pending intent. */ if ( askInFlightRef.current || - !!isSubmitting || store.get(revealedQueuedTurnFamily(immutableConversation?.conversationId ?? '')) != null || (!regenerateShaped && !isSubmittableMessage(text, availableFileCount)) ) { - return false; + return 'blocked'; } + if (isSubmitting) return 'pending'; if (!regenerateShaped && overrideFiles == null && files != null) { for (const file of files.values()) { if (file.progress < 1 && !isInlineablePastedText(file)) { - return false; + return 'pending'; } } } @@ -167,31 +174,34 @@ export function useTurns( /** The builder resolves `promptPrefix` on its copy; the pane's conversation stays as is. */ const conversation = immutableConversation == null ? null : { ...immutableConversation }; if (services.canSubmit?.(conversation) === false) { - return false; + return admission?.() === 'pending' ? 'pending' : 'blocked'; } - const codeDecision = resolveTurnCode(services.readCodeInputs(), conversation); - if (codeDecision == null) { - logger.warn('[useTurns] Refusing to send without an available code workspace'); - return false; + const codeResult = resolveTurnCodeResult(services.readCodeInputs(), conversation); + if (codeResult.state !== 'ready') { + if (!automatic) + logger.warn('[useTurns] Refusing to send without an available code workspace'); + return codeResult.state; } + const codeDecision = codeResult.decision; const endpoint = conversation?.endpoint; if (endpoint === null) { console.error('No endpoint available'); - return false; + return 'blocked'; } conversationId = conversationId ?? conversation?.conversationId ?? null; if (conversationId == 'search') { console.error('cannot send any message under search view!'); - return false; + return 'blocked'; } const cachedMessages = getMessages(conversationId); const isExistingConversation = conversationId != null && conversationId !== Constants.NEW_CONVO; if (isExistingConversation && overrideMessages == null && cachedMessages == null) { - logger.warn('[useTurns] Refusing to send before existing conversation history loads'); - return false; + if (!automatic) + logger.warn('[useTurns] Refusing to send before existing conversation history loads'); + return 'pending'; } /** @@ -204,22 +214,24 @@ export function useTurns( overrideMessages == null && isHistoryRevalidating(queryClient, conversationId) ) { - logger.warn('[useTurns] Refusing to send while conversation history revalidates'); - return false; + if (!automatic) + logger.warn('[useTurns] Refusing to send while conversation history revalidates'); + return 'pending'; } const latestMessage = getLatestMessage(); if (isContinued && !latestMessage) { console.error('cannot continue AI message without latestMessage!'); - return false; + return 'blocked'; } if (parentMessageId == null && hasPendingAssistantParent(latestMessage)) { - logger.warn( - '[useTurns] Refusing to append to a preliminary assistant message', - latestMessage, - ); - return false; + if (!automatic) + logger.warn( + '[useTurns] Refusing to append to a preliminary assistant message', + latestMessage, + ); + return 'pending'; } setShowStopButton(false); @@ -376,7 +388,10 @@ export function useTurns( isRegenerate: turn.regenerateShaped, isContinued, }); + return 'accepted'; }; + const ask: TAskFunction = (...args) => (submit(...args) === 'accepted' ? undefined : false); + const attempt = (text: string): Attempt => submit({ text }, undefined, true); - return { ask, regenerate: createRegenerate(ask, getMessages) }; + return { ask, attempt, regenerate: createRegenerate(ask, getMessages) }; } diff --git a/packages/chat/src/react/follow.ts b/packages/chat/src/react/follow.ts index cd25e19ac22..69c6cc29f51 100644 --- a/packages/chat/src/react/follow.ts +++ b/packages/chat/src/react/follow.ts @@ -63,8 +63,8 @@ export type FollowChatOptions = { onEvent?: (event: ChatEvent) => void; onFinish?: (result: ChatFinishResult) => void; /** - * A turn sent from here was stopped before the server kept anything of it. Its rows are gone - * from the list; its words were the reader's and can be offered back to them. + * A turn sent from here was stopped before the server kept anything of it. Preserve its words + * for the conversation's draft owner before awaited reconciliation can unmount this pane. */ onWithdrawn?: (turn: SubmittedTurn) => void; }; @@ -138,7 +138,8 @@ export type FollowedChat = { /** * Whether the conversation can take a turn at this instant: its stored messages are in, and no * generation is being started, followed, looked for or read back. Read when a turn is about to - * be built, since the answer a render holds can be a commit old. + * be built, since the answer a render holds can be a commit old. A refused check requests one + * render when its local phase becomes sendable again. */ canSend: () => boolean; /** @@ -257,6 +258,7 @@ export function useFollowChat({ onWithdrawn, }; const [attempt, setAttempt] = useState(0); + const [, notifyPhase] = useState(0); const [entry, setEntry] = useState(); const [load, setLoad] = useState({ id, attempt, state: 'loading' }); const [history, setHistory] = useState({ @@ -291,6 +293,7 @@ export function useFollowChat({ let reads = 0; /** The reader's stop in flight, which the turn it ends waits for instead of reattaching. */ let stopping: Promise | undefined; + let awaitingSend = false; const applier = createEventApplier({ schedule: perFrame, onEffect: (effect) => host.current.onEffect?.(effect), @@ -396,6 +399,7 @@ export function useFollowChat({ setHistory({ id, hasEarlier: earlier != null, isLoading: false, isError: false }); } finally { reads -= 1; + publishPhase(); } }; @@ -489,6 +493,7 @@ export function useFollowChat({ if (!stale) { setFollowing(false); setUnattached(!reached); + publishPhase(); } } if (owed) { @@ -523,6 +528,7 @@ export function useFollowChat({ return; } loaded = true; + publishPhase(); setLoad({ id, attempt, state: 'ready' }); /** * A run the caller signalled during the read had nothing to attach to until now. With the @@ -538,7 +544,7 @@ export function useFollowChat({ } }; - const canSend = (): boolean => + const eligible = (): boolean => !stale && loaded && !attaching && @@ -546,6 +552,20 @@ export function useFollowChat({ reads === 0 && (chat.status === 'ready' || chat.status === 'error'); + /** A refused eligibility check opts into one wake; read-only followers and accepted + * sends need no extra render. Phase completion is not a message/status snapshot change. */ + const canSend = (): boolean => { + const ready = eligible(); + if (!ready && !stale) awaitingSend = true; + return ready; + }; + const publishPhase = (): void => { + if (!stale && awaitingSend && eligible()) { + awaitingSend = false; + notifyPhase((revision) => revision + 1); + } + }; + /** * How a turn sent from here ended decides what follows it. * @@ -568,6 +588,11 @@ export function useFollowChat({ let own = current.foreign !== true && finished?.isDisconnect !== true && finished?.isSettled !== true; try { + /** Restitution belongs to the conversation, before any await can let its pane leave. + * Promotion can then move that draft; ordinary close/remount keeps it. */ + if (!stale && own && current.withdrawn === true) { + host.current.onWithdrawn?.(turn); + } if (stopped != null) { await stopped.catch(() => undefined); } @@ -583,9 +608,6 @@ export function useFollowChat({ if (completed != null) { await chat.setMessages(completed); } - if (!stale && current.withdrawn === true) { - host.current.onWithdrawn?.(turn); - } /** * However the turn ended, it may not leave its empty reply behind as one still on its * way: nothing more will fill it, and the next turn would be refused as answering a @@ -598,6 +620,7 @@ export function useFollowChat({ } finally { /** Only now can another turn be built: on the list this one left, not the one before it. */ driving = false; + publishPhase(); } if (stale) { return; From 9fc1027a6338d0ab49be4400d76f64f44e490e66 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:06 -0800 Subject: [PATCH 5/7] Complete Side Chat Intent Ownership and Query Readiness --- client/src/Providers/AgentsMapContext.tsx | 23 ++- .../src/components/Chat/Presentation.test.tsx | 46 +++++- client/src/components/Chat/Presentation.tsx | 6 +- .../__tests__/useAgentsCatalog.spec.tsx | 127 +++++++++++++++ .../useCodeWorkspace.admission.spec.tsx | 154 ++++++++++++++++++ client/src/hooks/Agents/useAgentsMap.ts | 44 ++--- client/src/hooks/Agents/useCodeWorkspace.ts | 10 +- .../hooks/Chat/__tests__/readiness.spec.tsx | 83 ++++++++++ client/src/hooks/Chat/ask/readiness.ts | 16 +- client/src/hooks/Chat/services.ts | 5 +- client/src/routes/Root.tsx | 22 ++- e2e/specs/mock/subagent-activity.spec.ts | 50 ++++-- packages/chat/src/components/pane/Driven.tsx | 4 +- .../components/side/__tests__/panel.spec.tsx | 122 +++++++++++++- packages/chat/src/components/side/panel.tsx | 38 ++--- .../chat/src/core/code/__tests__/turn.spec.ts | 28 ++++ packages/chat/src/core/code/turn.ts | 6 + packages/chat/src/core/code/workspace.ts | 6 +- .../src/react/chat/__tests__/driven.spec.tsx | 64 +++++++- packages/chat/src/react/chat/driven.ts | 18 +- packages/chat/src/react/chat/host.tsx | 2 + packages/chat/src/react/chat/turns.ts | 11 +- 22 files changed, 797 insertions(+), 88 deletions(-) create mode 100644 client/src/hooks/Agents/__tests__/useAgentsCatalog.spec.tsx create mode 100644 client/src/hooks/Agents/__tests__/useCodeWorkspace.admission.spec.tsx diff --git a/client/src/Providers/AgentsMapContext.tsx b/client/src/Providers/AgentsMapContext.tsx index e86c188aaf3..fcf666203d2 100644 --- a/client/src/Providers/AgentsMapContext.tsx +++ b/client/src/Providers/AgentsMapContext.tsx @@ -1,8 +1,29 @@ import { createContext, useContext } from 'react'; -import useAgentsMap from '~/hooks/Agents/useAgentsMap'; +import type { ReactNode } from 'react'; +import useAgentsMap, { useAgentsCatalog } from '~/hooks/Agents/useAgentsMap'; type AgentsMapContextType = ReturnType; /** Defaults to undefined (map unknown): an `{}` default outside the provider would * read as a loaded-but-empty catalog and misclassify stored agent picks as deleted. */ export const AgentsMapContext = createContext(undefined); export const useAgentsMapContext = () => useContext(AgentsMapContext); + +/** Separate lifecycle keeps the incremental map and its existing consumers compatible. */ +export const AgentsCatalogPendingContext = createContext(undefined); +export const useAgentsCatalogPending = () => useContext(AgentsCatalogPendingContext); + +/** One Root-owned catalog observer; existing readers still receive the incremental map. */ +export function AgentCatalogProvider({ + isAuthenticated, + children, +}: { + isAuthenticated: boolean; + children: ReactNode; +}) { + const { agentsMap, pending } = useAgentsCatalog({ isAuthenticated }); + return ( + + {children} + + ); +} diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx index 513f1d8aa61..4031c0c2551 100644 --- a/client/src/components/Chat/Presentation.test.tsx +++ b/client/src/components/Chat/Presentation.test.tsx @@ -12,6 +12,7 @@ import { sideChatAvailableAtom, } from '@librechat/chat/react'; import type { TConversation, TStartupConfig } from 'librechat-data-provider'; +import type { SideChat } from '@librechat/chat/react'; import type { JotaiStore } from 'test/harness'; import type { Artifact } from '~/common'; import { prepareUndockedDocument } from '~/components/Artifacts/undockedWindow'; @@ -39,6 +40,7 @@ const mockOpenChildLabel = 'Open Child Activity'; const mockSideChatLabel = 'Side chat loaded'; const mockOpenSideChatLabel = 'Open Side Chat'; const mockAskSideChatLabel = 'Ask for a side chat'; +let mockSideChatProps: { chat: SideChat; onHandedTextTaken: (expected: SideChat) => void }; const mockSelectAgentConversationLabel = 'Select Agent Conversation'; const mockStartAgentRunLabel = 'Start Agent Run'; /** @@ -86,7 +88,8 @@ jest.mock('@librechat/chat/components', () => { ), loadSideChatPanel: () => Promise.resolve({ - default: function MockSideChatPanel() { + default: function MockSideChatPanel(props: typeof mockSideChatProps) { + mockSideChatProps = props; const parent = useParentSubagents(); return (