Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion client/src/Providers/AgentsMapContext.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof useAgentsMap>;

/** 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<AgentsMapContextType>(undefined);
export const useAgentsMapContext = () => useContext(AgentsMapContext);

/** Separate lifecycle keeps the incremental map and its existing consumers compatible. */
export const AgentsCatalogPendingContext = createContext<boolean | undefined>(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 (
<AgentsCatalogPendingContext.Provider value={pending}>
<AgentsMapContext.Provider value={agentsMap}>{children}</AgentsMapContext.Provider>
</AgentsCatalogPendingContext.Provider>
);
}
6 changes: 6 additions & 0 deletions client/src/Providers/ChatHostContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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,
Expand Down
46 changes: 45 additions & 1 deletion client/src/components/Chat/Presentation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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';
/**
Expand Down Expand Up @@ -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 (
<aside>
Expand Down Expand Up @@ -430,6 +433,47 @@ describe('Presentation Artifact loading', () => {
);
});

it.each(['same', 'different'] as const)(
'an old pane callback cannot consume a newer %s destination handoff',
async (destination) => {
let atoms!: JotaiStore;
renderPresentation(
<ChatSurfaceHarness
seed={(store) => {
atoms = store;
}}
>
<RecoilRoot>
<Presentation>
<OpenSideChat />
</Presentation>
</RecoilRoot>
</ChatSurfaceHarness>,
);
fireEvent.click(screen.getByRole('button', { name: mockOpenSideChatLabel }));
await screen.findByText(mockSideChatLabel);
const conversation = atoms.get(sideChatAtom)!.conversation;
const captured = mockSideChatProps.chat;
const consume = mockSideChatProps.onHandedTextTaken;
act(() => {
atoms.set(sideChatAtom, {
conversation: {
...conversation,
conversationId: destination === 'same' ? conversation.conversationId : 'new-side',
},
text: 'Same question.',
});
});
const replacement = atoms.get(sideChatAtom)!;
expect(replacement).not.toBe(captured);
act(() => consume(captured));
expect(atoms.get(sideChatAtom)).toBe(replacement);
expect(atoms.get(sideChatAtom)?.text).toBe('Same question.');
act(() => mockSideChatProps.onHandedTextTaken(replacement));
expect(atoms.get(sideChatAtom)?.text).toBeUndefined();
},
);

it('shows a side chat beside the conversation, with child activity read for its own conversation', async () => {
renderPresentation(
<ChatSurfaceHarness>
Expand Down
11 changes: 9 additions & 2 deletions client/src/components/Chat/Presentation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { EModelEndpoint } from 'librechat-data-provider';
import { useRecoilValue, useSetRecoilState, useResetRecoilState } from 'recoil';
import {
sideChatAtom,
sideChatDraftSubmittedAtom,
SIDE_CHAT_PANE,
sideChatBesideAtom,
sideChatRequestAtom,
Expand All @@ -12,6 +13,7 @@ import {
SideChatHostProvider,
ParentSubagentsProvider,
} from '@librechat/chat/react';
import type { SideChat } from '@librechat/chat/react';
import useArtifactsRegistryLifetime from '~/hooks/Artifacts/useArtifactsRegistryLifetime';
import { MessageSurfaceContext } from '~/components/Chat/Messages/ui/surface';
import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';
Expand Down Expand Up @@ -70,9 +72,13 @@ export default function Presentation({
const sideChat = useAtomValue(sideChatAtom);
const isSideChatSubmitting = useIsSubmitting(SIDE_CHAT_PANE);
const setSideChat = useSetAtom(sideChatAtom);
const submitSideChatDraft = useSetAtom(sideChatDraftSubmittedAtom);
const closeSideChat = useCallback(() => setSideChat(null), [setSideChat]);
const takeSideChatText = useCallback(
() => setSideChat((current) => current && { conversation: current.conversation }),
(expected: SideChat) =>
setSideChat((current) =>
current === expected ? { conversation: current.conversation } : current,
),
[setSideChat],
);
const previousConversationIdRef = useRef<string | null>(null);
Expand Down Expand Up @@ -227,12 +233,13 @@ export default function Presentation({
chat={sideChat}
onClose={closeSideChat}
onHandedTextTaken={takeSideChatText}
onDraftSubmitted={submitSideChatDraft}
/>
</Suspense>
</ParentSubagentsProvider>
</SideChatHostProvider>
);
}, [closeSideChat, isSideChatSubmitting, sideChat, takeSideChatText]);
}, [closeSideChat, isSideChatSubmitting, sideChat, submitSideChatDraft, takeSideChatText]);

/* Undocked, the pane renders into its own window: the side panel gives its
* width back to the conversation instead of holding an empty column. */
Expand Down
157 changes: 157 additions & 0 deletions client/src/hooks/Agents/__tests__/useAgentsCatalog.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider, onlineManager } from '@tanstack/react-query';
import { QueryKeys, EModelEndpoint, PermissionBits, dataService } from 'librechat-data-provider';
import type { AgentListResponse } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import { activateCatalog, resetCatalogWarmup } from '~/hooks/useCatalogWarmup';
import useAgentsMap, { useAgentsCatalog } from '../useAgentsMap';

jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return { ...actual, dataService: { ...actual.dataService, listAgents: jest.fn() } };
});
const list = jest.mocked(dataService.listAgents);
const page = (id: string, after: string | null = null): AgentListResponse =>
({
object: 'list',
data: [{ id, name: id }],
first_id: id,
last_id: id,
has_more: after != null,
after,
}) as AgentListResponse;
const denied = Object.assign(new Error('denied'), {
isAxiosError: true,
response: { status: 403 },
});
function setup({
enabled,
available = true,
authenticated = true,
client: supplied,
}: { enabled?: boolean; available?: boolean; authenticated?: boolean; client?: QueryClient } = {}) {
const client =
supplied ??
new QueryClient({
defaultOptions: { queries: { retry: false } },
logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() },
});
client.setQueryData([QueryKeys.endpoints], available ? { [EModelEndpoint.agents]: {} } : {});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
);
return {
client,
...renderHook(
() => ({
catalog: useAgentsCatalog({ isAuthenticated: authenticated, enabled }),
legacy: useAgentsMap({ isAuthenticated: authenticated, enabled }),
}),
{ wrapper },
),
};
}
beforeEach(() => {
list.mockReset();
resetCatalogWarmup();
activateCatalog('agents');
});
afterEach(() => onlineManager.setOnline(true));

it.each(['present', 'missing', 'failure'] as const)(
'keeps incremental metadata pending until the next page settles: %s',
async (outcome) => {
let release!: (value: AgentListResponse) => void;
let reject!: (error: Error) => void;
list.mockResolvedValueOnce(page('root', 'next')).mockImplementationOnce(
() =>
new Promise((yes, no) => {
release = yes;
reject = no;
}),
);
const { result, rerender } = setup();
await waitFor(() => expect(list).toHaveBeenCalledTimes(2));
expect(result.current.catalog.agentsMap?.root).toBeDefined();
expect(result.current.catalog.agentsMap?.child).toBeUndefined();
expect(result.current.catalog.pending).toBe(true);
expect(result.current.legacy).toEqual(result.current.catalog.agentsMap);
const first = result.current.catalog.agentsMap;
const legacy = result.current.legacy;
rerender();
expect(result.current.catalog.agentsMap).toBe(first);
expect(result.current.legacy).toBe(legacy);
await act(async () =>
outcome === 'failure'
? reject(denied)
: release(page(outcome === 'present' ? 'child' : 'other')),
);
await waitFor(() => expect(result.current.catalog.pending).toBe(false));
expect(Boolean(result.current.catalog.agentsMap?.child)).toBe(outcome === 'present');
expect(result.current.catalog.agentsMap?.root).toBeDefined();
expect(list).toHaveBeenCalledTimes(2);
},
);

it('settles an initial failure instead of preserving unknown metadata forever', async () => {
list.mockRejectedValue(denied);
const { result } = setup();
await waitFor(() => expect(result.current.catalog.pending).toBe(false));
expect(result.current.catalog.agentsMap).toBeUndefined();
expect(list).toHaveBeenCalledTimes(1);
});
it('keeps an offline query pending until its native owner resumes', async () => {
onlineManager.setOnline(false);
list.mockResolvedValue(page('root'));
const { result } = setup();
expect(result.current.catalog.pending).toBe(true);
expect(list).not.toHaveBeenCalled();
act(() => onlineManager.setOnline(true));
await waitFor(() => expect(result.current.catalog.pending).toBe(false));
expect(list).toHaveBeenCalledTimes(1);
});
it.each([{ enabled: false }, { available: false }, { authenticated: false }])(
'does not wait for a disabled or unavailable owner: %j',
(options) => {
const { result } = setup(options);
expect(result.current.catalog.pending).toBe(false);
expect(list).not.toHaveBeenCalled();
},
);
it('retains a warmup wait without starting an eager request', async () => {
resetCatalogWarmup();
list.mockResolvedValue(page('root'));
const { result } = setup();
expect(result.current.catalog.pending).toBe(true);
expect(list).not.toHaveBeenCalled();
act(() => activateCatalog('agents'));
await waitFor(() => expect(result.current.catalog.pending).toBe(false));
expect(list).toHaveBeenCalledTimes(1);
});

it.each(['complete', 'error'] as const)(
'keeps unreleased warmup pending with stale cached %s data',
async (cached) => {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() },
});
const key = [QueryKeys.agents, { requiredPermission: PermissionBits.VIEW }];
client.setQueryData(
key,
{ pages: [page('old-root')], pageParams: [undefined] },
{ updatedAt: Date.now() - 10000 },
);
if (cached === 'error')
await client.fetchInfiniteQuery(key, () => Promise.reject(denied)).catch(() => undefined);
resetCatalogWarmup();
list.mockResolvedValue(page('new-child'));
const { result } = setup({ client });
expect(result.current.catalog.pending).toBe(true);
expect(list).not.toHaveBeenCalled();
act(() => activateCatalog('agents'));
await waitFor(() => expect(result.current.catalog.pending).toBe(false));
expect(result.current.catalog.agentsMap?.['new-child']).toBeDefined();
expect(list).toHaveBeenCalledTimes(1);
},
);
Loading
Loading