LibreChat/client/src/hooks/Conversations/useNavigateToConvo.tsx
Danny Avila b5ab32c5ae
🎯 refactor: Centralize Agent Model Handling Across Conversation Lifecycle (#10956)
* refactor: Implement clearModelForNonEphemeralAgent utility for improved agent handling

- Introduced clearModelForNonEphemeralAgent function to manage model state for non-ephemeral agents across various components.
- Updated ModelSelectorContext to initialize model based on agent type.
- Enhanced useNavigateToConvo, useQueryParams, and useSelectMention hooks to clear model for non-ephemeral agents.
- Refactored buildDefaultConvo and endpoints utility to ensure proper handling of agent_id and model state.
- Improved overall conversation logic and state management for better performance and reliability.

* refactor: Enhance useNewConvo hook to improve agent conversation handling

- Added logic to skip access checks for existing agent conversations, utilizing localStorage to restore conversations after refresh.
- Improved handling of default endpoints for agents based on user access and existing conversation state, ensuring more reliable conversation initialization.

* refactor: Update ChatRoute and useAuthRedirect to include user roles

- Enhanced ChatRoute to utilize user roles for improved conversation state management.
- Modified useAuthRedirect to return user roles alongside authentication status, ensuring roles are available for conditional logic in ChatRoute.
- Adjusted conversation initialization logic to depend on the loaded roles, enhancing the reliability of the conversation setup.

* refactor: Update BaseClient to handle non-ephemeral agents in conversation logic

- Added a check for non-ephemeral agents in BaseClient, modifying the exceptions set to include 'model' when applicable.
- Enhanced conversation handling to improve flexibility based on agent type.

* test: Add mock for clearModelForNonEphemeralAgent in useQueryParams tests

- Introduced a mock for clearModelForNonEphemeralAgent to enhance testing of query parameters related to non-ephemeral agents.
- This addition supports improved test coverage and ensures proper handling of model state in relevant scenarios.

* refactor: Simplify mocks in useQueryParams tests for improved clarity

- Updated the mocking strategy for utilities in useQueryParams tests to use actual implementations where possible, while still suppressing test output for the logger.
- Enhanced the mock for tQueryParamsSchema to minimize complexity and avoid unnecessary validation during tests, improving test reliability and maintainability.

* refactor: Enhance agent identification logic in BaseClient for improved clarity

* chore: Import Constants in families.ts for enhanced functionality
2025-12-13 08:29:15 -05:00

132 lines
4.5 KiB
TypeScript

import { useCallback } from 'react';
import { useSetRecoilState } from 'recoil';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys, Constants, dataService, getEndpointField } from 'librechat-data-provider';
import type {
TEndpointsConfig,
TStartupConfig,
TModelsConfig,
TConversation,
} from 'librechat-data-provider';
import {
clearModelForNonEphemeralAgent,
getDefaultEndpoint,
clearMessagesCache,
buildDefaultConvo,
logger,
} from '~/utils';
import { useApplyModelSpecEffects } from '~/hooks/Agents';
import store from '~/store';
const useNavigateToConvo = (index = 0) => {
const navigate = useNavigate();
const queryClient = useQueryClient();
const clearAllConversations = store.useClearConvoState();
const applyModelSpecEffects = useApplyModelSpecEffects();
const setSubmission = useSetRecoilState(store.submissionByIndex(index));
const clearAllLatestMessages = store.useClearLatestMessages(`useNavigateToConvo ${index}`);
const { hasSetConversation, setConversation: setConvo } = store.useCreateConversationAtom(index);
const setConversation = useCallback(
(conversation: TConversation) => {
setConvo(conversation);
if (!conversation.spec) {
return;
}
const startupConfig = queryClient.getQueryData<TStartupConfig>([QueryKeys.startupConfig]);
applyModelSpecEffects({
startupConfig,
specName: conversation?.spec,
convoId: conversation.conversationId,
});
},
[setConvo, queryClient, applyModelSpecEffects],
);
const fetchFreshData = async (conversation?: Partial<TConversation>) => {
const conversationId = conversation?.conversationId;
if (!conversationId) {
return;
}
try {
const data = await queryClient.fetchQuery([QueryKeys.conversation, conversationId], () =>
dataService.getConversationById(conversationId),
);
logger.log('conversation', 'Fetched fresh conversation data', data);
const convoData = { ...data };
clearModelForNonEphemeralAgent(convoData);
setConversation(convoData);
navigate(`/c/${conversationId ?? Constants.NEW_CONVO}`, { state: { focusChat: true } });
} catch (error) {
console.error('Error fetching conversation data on navigation', error);
if (conversation) {
setConversation(conversation as TConversation);
navigate(`/c/${conversationId}`, { state: { focusChat: true } });
}
}
};
const navigateToConvo = (
conversation?: TConversation | null,
options?: {
resetLatestMessage?: boolean;
currentConvoId?: string;
},
) => {
if (!conversation) {
logger.warn('conversation', 'Conversation not provided to `navigateToConvo`');
return;
}
const { resetLatestMessage = true, currentConvoId } = options || {};
logger.log('conversation', 'Navigating to conversation', conversation);
hasSetConversation.current = true;
setSubmission(null);
if (resetLatestMessage) {
logger.log('latest_message', 'Clearing all latest messages');
clearAllLatestMessages();
}
let convo = { ...conversation };
const endpointsConfig = queryClient.getQueryData<TEndpointsConfig>([QueryKeys.endpoints]);
if (!convo.endpoint || !endpointsConfig?.[convo.endpoint]) {
/* undefined/removed endpoint edge case */
const modelsConfig = queryClient.getQueryData<TModelsConfig>([QueryKeys.models]);
const defaultEndpoint = getDefaultEndpoint({
convoSetup: conversation,
endpointsConfig,
});
const endpointType = getEndpointField(endpointsConfig, defaultEndpoint, 'type');
if (!conversation.endpointType && endpointType) {
conversation.endpointType = endpointType;
}
const models = modelsConfig?.[defaultEndpoint ?? ''] ?? [];
convo = buildDefaultConvo({
models,
conversation,
endpoint: defaultEndpoint,
lastConversationSetup: conversation,
});
}
clearAllConversations(true);
clearMessagesCache(queryClient, currentConvoId);
if (convo.conversationId !== Constants.NEW_CONVO && convo.conversationId) {
queryClient.invalidateQueries([QueryKeys.conversation, convo.conversationId]);
fetchFreshData(convo);
} else {
setConversation(convo);
navigate(`/c/${convo.conversationId ?? Constants.NEW_CONVO}`, { state: { focusChat: true } });
}
};
return {
navigateToConvo,
};
};
export default useNavigateToConvo;