Skip to content
41 changes: 39 additions & 2 deletions client/src/Providers/SubagentsHostContext.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useMemo, useRef, useState } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { CSSTransition } from 'react-transition-group';
import { setDefaultSubagentsHost } from '@librechat/chat/react';
import { createGenerationTransport } from '@librechat/chat';
import { SteerPart, ScrollToBottom } from '@librechat/chat/components';
import { ForkOptions, QueryKeys, dataService } from 'librechat-data-provider';
import { useFollowChat, setDefaultSubagentsHost } from '@librechat/chat/react';
import type {
FollowedChat,
SubagentsHost,
MessagePartsHost,
TaskContentScope,
Expand All @@ -20,10 +22,12 @@ import type {
} from '@librechat/chat/react';
import type { ToolCallPartParams } from 'librechat-data-provider';
import {
fetchStreamStatus,
useToolCallPartQuery,
useForkConvoMutation,
useSubagentThreadQuery,
useSubagentControlMutation,
useSubagentThreadToolCallPartQuery,
} from '~/data-provider';
import {
useSubagentTaskContentQuery,
Expand All @@ -34,7 +38,9 @@ import useNavigateToConvo from '~/hooks/Conversations/useNavigateToConvo';
import { ARTIFACTS_SHEET_MAX_WIDTH } from '~/utils/breakpoints';
import { useConfiguredFooter } from '~/components/Chat/Footer';
import useScaledMaxWidth from '~/hooks/useScaledMaxWidth';
import { useChatTransport } from './ChatTransportContext';
import { useAgentsMapContext } from './AgentsMapContext';
import { useChatSettings } from './ChatSettingsContext';

/** Reads a shortened guidance message's full receipt, once the reader asks for it. */
function useRetainedControl(
Expand Down Expand Up @@ -114,6 +120,35 @@ function useThread(
};
}

/**
* Follows a child thread as a conversation: its messages through the parent-scoped route, and
* the generation job that streams a background child, over the transport main chat streams on.
*/
function useThreadChat(
parentConversationId: string,
threadId: string,
{ live, enabled }: { live: boolean; enabled: boolean },
): FollowedChat {
const { token } = useChatSettings().auth;
const transport = useChatTransport();
const generation = useMemo(
() =>
createGenerationTransport({
wire: () => transport.stream({ token }),
getStatus: fetchStreamStatus,
}),
[transport, token],
);
const loadMessages = useCallback(
() =>
dataService.getSubagentThreadMessages(parentConversationId, threadId, {
toolPreviews: true,
}),
[parentConversationId, threadId],
);
return useFollowChat({ id: threadId, transport: generation, loadMessages, live, enabled });
}

function useControl(
handlers: Parameters<SubagentsHost['useControl']>[0],
): ReturnType<SubagentsHost['useControl']> {
Expand Down Expand Up @@ -199,6 +234,8 @@ export const appSubagentsHost: SubagentsHost = {
useToolContent: useSubagentToolContentQuery,
useAgentsMap: useAgentsMapContext,
useChildPartsHost,
useThreadChat,
useThreadToolContent: useSubagentThreadToolCallPartQuery,
useThread,
loadThread: (...args) => dataService.getSubagentThread(...args),
useControl,
Expand Down
145 changes: 145 additions & 0 deletions client/src/Providers/__tests__/SubagentsHostFollow.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { renderHook, waitFor } from '@testing-library/react';
import { TaskContentScopeContext } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage, ToolCallPartParams } from 'librechat-data-provider';

const mockThreadMessages = jest.fn();
const mockThreadToolCallPart = jest.fn();
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: {
...actual.dataService,
getSubagentThreadMessages: (...args: unknown[]) => mockThreadMessages(...args),
getSubagentThreadToolCallPart: (...args: unknown[]) => mockThreadToolCallPart(...args),
},
};
});

const mockStreamStatus = jest.fn();
jest.mock('~/data-provider/SSE/queries', () => ({
...jest.requireActual('~/data-provider/SSE/queries'),
fetchStreamStatus: (...args: unknown[]) => mockStreamStatus(...args),
}));

const { appSubagentsHost } = jest.requireActual('~/Providers/SubagentsHostContext');

const brief = {
messageId: 'task:user',
conversationId: 'child-thread',
parentMessageId: null,
isCreatedByUser: true,
text: 'Investigate the release.',
} as TMessage;

const wrapper =
(scope?: { parentConversationId: string; threadId: string; taskId: string }) =>
({ children }: { children: React.ReactNode }) => {
const [client] = React.useState(
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
);
return (
<RecoilRoot>
<QueryClientProvider client={client}>
<TaskContentScopeContext.Provider value={scope ?? null}>
{children}
</TaskContentScopeContext.Provider>
</QueryClientProvider>
</RecoilRoot>
);
};

describe("the app's subagents host, following a child thread", () => {
beforeEach(() => {
mockThreadMessages.mockReset();
mockThreadToolCallPart.mockReset();
mockStreamStatus.mockReset();
});

it("reads the thread's messages through its parent, with tool previews", async () => {
mockStreamStatus.mockResolvedValue({ active: false });
mockThreadMessages.mockResolvedValue([brief]);

const { result } = renderHook(
() =>
appSubagentsHost.useThreadChat('parent-conversation', 'child-thread', {
live: false,
enabled: true,
}),
{ wrapper: wrapper() },
);
expect(result.current.isLoading).toBe(true);

await waitFor(() => expect(result.current.messages).toEqual([brief]));
expect(mockStreamStatus).toHaveBeenCalledWith('child-thread');
expect(mockThreadMessages).toHaveBeenCalledWith('parent-conversation', 'child-thread', {
toolPreviews: true,
});
expect(result.current.isLoading).toBe(false);
});

it('reports messages it could not read instead of an empty thread', async () => {
mockStreamStatus.mockResolvedValue({ active: false });
mockThreadMessages.mockRejectedValue(new Error('not found'));

const { result } = renderHook(
() =>
appSubagentsHost.useThreadChat('parent-conversation', 'child-thread', {
live: false,
enabled: true,
}),
{ wrapper: wrapper() },
);

await waitFor(() => expect(result.current.isLoadError).toBe(true));
});

it('reads nothing for a selection that has no thread to follow', async () => {
renderHook(
() =>
appSubagentsHost.useThreadChat('parent-conversation', '', { live: false, enabled: false }),
{ wrapper: wrapper() },
);
await Promise.resolve();

expect(mockStreamStatus).not.toHaveBeenCalled();
expect(mockThreadMessages).not.toHaveBeenCalled();
});

const params: ToolCallPartParams = {
conversationId: 'child-thread',
messageId: 'task:assistant',
partIndex: 1,
toolCallId: 'call-1',
};

it("reads a tool call's full output through the parent the task scope names", async () => {
const part = { type: 'tool_call', tool_call: { id: 'call-1', output: 'whole output' } };
mockThreadToolCallPart.mockResolvedValue(part);
const scope = {
parentConversationId: 'parent-conversation',
threadId: 'child-thread',
taskId: 'task',
};

const { result } = renderHook(() => appSubagentsHost.useThreadToolContent(params), {
wrapper: wrapper(scope),
});

await waitFor(() => expect(result.current.data).toEqual(part));
expect(mockThreadToolCallPart).toHaveBeenCalledWith('parent-conversation', params);
});

it('asks for nothing outside a task scope, where it could not name the parent', async () => {
const { result } = renderHook(() => appSubagentsHost.useThreadToolContent(params), {
wrapper: wrapper(),
});
await Promise.resolve();

expect(result.current.fetchStatus).toBe('idle');
expect(mockThreadToolCallPart).not.toHaveBeenCalled();
});
});
48 changes: 45 additions & 3 deletions client/src/data-provider/Subagents/queries.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { useMemo } from 'react';
import { useContext, useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Constants, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';
import { ACTIVE_THREAD_REFRESH_MS, subagentThreadHasTaskEvidence } from '@librechat/chat/react';
import {
TaskContentScopeContext,
ACTIVE_THREAD_REFRESH_MS,
subagentThreadHasTaskEvidence,
} from '@librechat/chat/react';
import type {
ParentSubagentIndex,
ToolCallPartResponse,
SubagentControlReceipt,
SubagentControlResponse,
SubagentThreadView,
} from 'librechat-data-provider';
import type { SubagentControlVariables, ToolContentQuery } from '@librechat/chat/react';
import type { UseQueryOptions, QueryObserverResult } from '@tanstack/react-query';
import type { SubagentControlVariables } from '@librechat/chat/react';

export { ACTIVE_THREAD_REFRESH_MS, subagentThreadHasTaskEvidence };
export type { SubagentControlVariables };
Expand Down Expand Up @@ -213,3 +218,40 @@ export const useSubagentControlMutation = (options: SubagentControlMutationOptio
},
);
};

/**
* The full tool call behind a preview in a followed child thread, read through the parent
* conversation the task scope names: the ordinary message route answers 404 for a child thread.
* Cached by the call's identity, as `useToolCallPartQuery` is.
*/
export const useSubagentThreadToolCallPartQuery: ToolContentQuery = (
params,
config,
revision = '',
) => {
const scope = useContext(TaskContentScopeContext);
const parentConversationId = scope?.parentConversationId ?? '';
const { conversationId, messageId, toolCallId, stepId, agentId } = params;
return useQuery<ToolCallPartResponse>(
[
QueryKeys.subagentThreadToolCallPart,
parentConversationId,
conversationId,
messageId,
toolCallId ?? '',
stepId ?? '',
agentId ?? '',
revision,
],
() => dataService.getSubagentThreadToolCallPart(parentConversationId, params),
{
staleTime: Infinity,
retry: 1,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
...config,
enabled: scope != null && config?.enabled !== false,
},
);
};
Loading
Loading