2024-06-25 03:02:38 -04:00
|
|
|
import { useCallback, useState } from 'react';
|
2025-12-11 21:19:43 -05:00
|
|
|
import { QueryKeys, isAssistantsEndpoint } from 'librechat-data-provider';
|
2025-04-29 03:49:02 -04:00
|
|
|
import { useQueryClient } from '@tanstack/react-query';
|
2024-06-25 03:02:38 -04:00
|
|
|
import { useRecoilState, useResetRecoilState, useSetRecoilState } from 'recoil';
|
|
|
|
|
import type { TMessage } from 'librechat-data-provider';
|
2025-12-11 21:19:43 -05:00
|
|
|
import { useAbortStreamMutation, useGetMessagesByConvoId } from '~/data-provider';
|
2024-06-25 03:02:38 -04:00
|
|
|
import useChatFunctions from '~/hooks/Chat/useChatFunctions';
|
|
|
|
|
import { useAuthContext } from '~/hooks/AuthContext';
|
|
|
|
|
import useNewConvo from '~/hooks/useNewConvo';
|
|
|
|
|
import store from '~/store';
|
|
|
|
|
|
|
|
|
|
// this to be set somewhere else
|
|
|
|
|
export default function useChatHelpers(index = 0, paramId?: string) {
|
|
|
|
|
const clearAllSubmissions = store.useClearSubmissionState();
|
|
|
|
|
const [files, setFiles] = useRecoilState(store.filesByIndex(index));
|
|
|
|
|
const [filesLoading, setFilesLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const { isAuthenticated } = useAuthContext();
|
2025-12-11 21:19:43 -05:00
|
|
|
const abortMutation = useAbortStreamMutation();
|
2024-06-25 03:02:38 -04:00
|
|
|
|
|
|
|
|
const { newConversation } = useNewConvo(index);
|
|
|
|
|
const { useCreateConversationAtom } = store;
|
|
|
|
|
const { conversation, setConversation } = useCreateConversationAtom(index);
|
2025-12-11 21:19:43 -05:00
|
|
|
const { conversationId, endpoint, endpointType } = conversation ?? {};
|
2024-06-25 03:02:38 -04:00
|
|
|
|
🧭 refactor: Modernize Nav/Header (#7094)
* refactor: streamline model preset handling in conversation setup
* refactor: integrate navigation and location hooks in chat functions and event handlers, prevent cache from fetching on final event handling
* fix: prevent adding code interpreter non-image output to file list on message attachment event, fix all unhandled edge cases when this is done (treating the file download as an image attachment, undefined fields, message tokenCount issues, use of `startsWith` on undefined "text") although it is now prevent altogether
* chore: remove unused jailbreak prop from MinimalIcon component in EndpointIcon
* feat: add new SVG icons (MobileSidebar, Sidebar, XAIcon), fix: xAI styling in dark vs. light modes, adjust styling of Landing icons
* fix: open conversation in new tab on navigation with ctrl/meta key
* refactor: update Nav & Header to use close/open sidebar buttons, as well as redesign "New Chat"/"Bookmarks" buttons to the top of the Nav, matching the latest design of ChatGPT for simplicity and to free up space
* chore: remove unused isToggleHovering state and simplify opacity logic in Nav component
* style: match mobile nav to mobile header
2025-04-27 14:03:25 -04:00
|
|
|
const queryParam = paramId === 'new' ? paramId : (conversationId ?? paramId ?? '');
|
2024-06-25 03:02:38 -04:00
|
|
|
|
|
|
|
|
/* Messages: here simply to fetch, don't export and use `getMessages()` instead */
|
🧭 refactor: Modernize Nav/Header (#7094)
* refactor: streamline model preset handling in conversation setup
* refactor: integrate navigation and location hooks in chat functions and event handlers, prevent cache from fetching on final event handling
* fix: prevent adding code interpreter non-image output to file list on message attachment event, fix all unhandled edge cases when this is done (treating the file download as an image attachment, undefined fields, message tokenCount issues, use of `startsWith` on undefined "text") although it is now prevent altogether
* chore: remove unused jailbreak prop from MinimalIcon component in EndpointIcon
* feat: add new SVG icons (MobileSidebar, Sidebar, XAIcon), fix: xAI styling in dark vs. light modes, adjust styling of Landing icons
* fix: open conversation in new tab on navigation with ctrl/meta key
* refactor: update Nav & Header to use close/open sidebar buttons, as well as redesign "New Chat"/"Bookmarks" buttons to the top of the Nav, matching the latest design of ChatGPT for simplicity and to free up space
* chore: remove unused isToggleHovering state and simplify opacity logic in Nav component
* style: match mobile nav to mobile header
2025-04-27 14:03:25 -04:00
|
|
|
|
2024-06-25 03:02:38 -04:00
|
|
|
const { data: _messages } = useGetMessagesByConvoId(conversationId ?? '', {
|
|
|
|
|
enabled: isAuthenticated,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const resetLatestMessage = useResetRecoilState(store.latestMessageFamily(index));
|
|
|
|
|
const [isSubmitting, setIsSubmitting] = useRecoilState(store.isSubmittingFamily(index));
|
|
|
|
|
const [latestMessage, setLatestMessage] = useRecoilState(store.latestMessageFamily(index));
|
|
|
|
|
const setSiblingIdx = useSetRecoilState(
|
|
|
|
|
store.messagesSiblingIdxFamily(latestMessage?.parentMessageId ?? null),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const setMessages = useCallback(
|
|
|
|
|
(messages: TMessage[]) => {
|
|
|
|
|
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, queryParam], messages);
|
🧭 refactor: Modernize Nav/Header (#7094)
* refactor: streamline model preset handling in conversation setup
* refactor: integrate navigation and location hooks in chat functions and event handlers, prevent cache from fetching on final event handling
* fix: prevent adding code interpreter non-image output to file list on message attachment event, fix all unhandled edge cases when this is done (treating the file download as an image attachment, undefined fields, message tokenCount issues, use of `startsWith` on undefined "text") although it is now prevent altogether
* chore: remove unused jailbreak prop from MinimalIcon component in EndpointIcon
* feat: add new SVG icons (MobileSidebar, Sidebar, XAIcon), fix: xAI styling in dark vs. light modes, adjust styling of Landing icons
* fix: open conversation in new tab on navigation with ctrl/meta key
* refactor: update Nav & Header to use close/open sidebar buttons, as well as redesign "New Chat"/"Bookmarks" buttons to the top of the Nav, matching the latest design of ChatGPT for simplicity and to free up space
* chore: remove unused isToggleHovering state and simplify opacity logic in Nav component
* style: match mobile nav to mobile header
2025-04-27 14:03:25 -04:00
|
|
|
if (queryParam === 'new' && conversationId && conversationId !== 'new') {
|
2024-06-25 03:02:38 -04:00
|
|
|
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, conversationId], messages);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
[queryParam, queryClient, conversationId],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const getMessages = useCallback(() => {
|
|
|
|
|
return queryClient.getQueryData<TMessage[]>([QueryKeys.messages, queryParam]);
|
|
|
|
|
}, [queryParam, queryClient]);
|
|
|
|
|
|
|
|
|
|
/* Conversation */
|
|
|
|
|
// const setActiveConvos = useSetRecoilState(store.activeConversations);
|
|
|
|
|
|
|
|
|
|
// const setConversation = useCallback(
|
|
|
|
|
// (convoUpdate: TConversation) => {
|
|
|
|
|
// _setConversation(prev => {
|
|
|
|
|
// const { conversationId: convoId } = prev ?? { conversationId: null };
|
|
|
|
|
// const { conversationId: currentId } = convoUpdate;
|
|
|
|
|
// if (currentId && convoId && convoId !== 'new' && convoId !== currentId) {
|
|
|
|
|
// // for now, we delete the prev convoId from activeConversations
|
|
|
|
|
// const newActiveConvos = { [currentId]: true };
|
|
|
|
|
// setActiveConvos(newActiveConvos);
|
|
|
|
|
// }
|
|
|
|
|
// return convoUpdate;
|
|
|
|
|
// });
|
|
|
|
|
// },
|
|
|
|
|
// [_setConversation, setActiveConvos],
|
|
|
|
|
// );
|
|
|
|
|
|
|
|
|
|
const setSubmission = useSetRecoilState(store.submissionByIndex(index));
|
|
|
|
|
|
|
|
|
|
const { ask, regenerate } = useChatFunctions({
|
|
|
|
|
index,
|
|
|
|
|
files,
|
|
|
|
|
setFiles,
|
|
|
|
|
getMessages,
|
|
|
|
|
setMessages,
|
|
|
|
|
isSubmitting,
|
|
|
|
|
conversation,
|
|
|
|
|
latestMessage,
|
|
|
|
|
setSubmission,
|
|
|
|
|
setLatestMessage,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const continueGeneration = () => {
|
|
|
|
|
if (!latestMessage) {
|
|
|
|
|
console.error('Failed to regenerate the message: latestMessage not found.');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const messages = getMessages();
|
|
|
|
|
|
|
|
|
|
const parentMessage = messages?.find(
|
|
|
|
|
(element) => element.messageId == latestMessage.parentMessageId,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (parentMessage && parentMessage.isCreatedByUser) {
|
|
|
|
|
ask({ ...parentMessage }, { isContinued: true, isRegenerate: true, isEdited: true });
|
|
|
|
|
} else {
|
|
|
|
|
console.error(
|
|
|
|
|
'Failed to regenerate the message: parentMessage not found, or not created by user.',
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2025-12-11 21:19:43 -05:00
|
|
|
/**
|
|
|
|
|
* Stop generation - for non-assistants endpoints, calls abort endpoint first.
|
|
|
|
|
* The abort endpoint will cause the backend to emit a `done` event with `aborted: true`,
|
|
|
|
|
* which will be handled by the SSE event handler to clean up UI.
|
|
|
|
|
* Assistants endpoint has its own abort mechanism via useEventHandlers.abortConversation.
|
|
|
|
|
*/
|
|
|
|
|
const stopGenerating = useCallback(async () => {
|
|
|
|
|
const actualEndpoint = endpointType ?? endpoint;
|
|
|
|
|
const isAssistants = isAssistantsEndpoint(actualEndpoint);
|
|
|
|
|
console.log('[useChatHelpers] stopGenerating called', {
|
|
|
|
|
conversationId,
|
|
|
|
|
endpoint,
|
|
|
|
|
endpointType,
|
|
|
|
|
actualEndpoint,
|
|
|
|
|
isAssistants,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// For non-assistants endpoints (using resumable streams), call abort endpoint first
|
|
|
|
|
if (conversationId && !isAssistants) {
|
|
|
|
|
try {
|
|
|
|
|
console.log('[useChatHelpers] Calling abort mutation for:', conversationId);
|
|
|
|
|
await abortMutation.mutateAsync({ conversationId });
|
|
|
|
|
console.log('[useChatHelpers] Abort mutation succeeded');
|
|
|
|
|
// The SSE will receive a `done` event with `aborted: true` and clean up
|
|
|
|
|
// We still clear submissions as a fallback
|
|
|
|
|
clearAllSubmissions();
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('[useChatHelpers] Abort failed:', error);
|
|
|
|
|
// Fall back to clearing submissions
|
|
|
|
|
clearAllSubmissions();
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// For assistants endpoints, just clear submissions (existing behavior)
|
|
|
|
|
console.log('[useChatHelpers] Assistants endpoint, just clearing submissions');
|
|
|
|
|
clearAllSubmissions();
|
|
|
|
|
}
|
|
|
|
|
}, [conversationId, endpoint, endpointType, abortMutation, clearAllSubmissions]);
|
2024-06-25 03:02:38 -04:00
|
|
|
|
|
|
|
|
const handleStopGenerating = (e: React.MouseEvent<HTMLButtonElement>) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
stopGenerating();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleRegenerate = (e: React.MouseEvent<HTMLButtonElement>) => {
|
|
|
|
|
e.preventDefault();
|
2025-01-06 10:32:44 -05:00
|
|
|
const parentMessageId = latestMessage?.parentMessageId ?? '';
|
2024-06-25 03:02:38 -04:00
|
|
|
if (!parentMessageId) {
|
|
|
|
|
console.error('Failed to regenerate the message: parentMessageId not found.');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
regenerate({ parentMessageId });
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleContinue = (e: React.MouseEvent<HTMLButtonElement>) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
continueGeneration();
|
|
|
|
|
setSiblingIdx(0);
|
|
|
|
|
};
|
|
|
|
|
|
2025-11-25 15:20:07 -05:00
|
|
|
const [preset, setPreset] = useRecoilState(store.presetByIndex(index));
|
2024-06-25 03:02:38 -04:00
|
|
|
const [showPopover, setShowPopover] = useRecoilState(store.showPopoverFamily(index));
|
|
|
|
|
const [abortScroll, setAbortScroll] = useRecoilState(store.abortScrollFamily(index));
|
|
|
|
|
const [optionSettings, setOptionSettings] = useRecoilState(store.optionSettingsFamily(index));
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
newConversation,
|
|
|
|
|
conversation,
|
|
|
|
|
setConversation,
|
|
|
|
|
// getConvos,
|
|
|
|
|
// setConvos,
|
|
|
|
|
isSubmitting,
|
|
|
|
|
setIsSubmitting,
|
|
|
|
|
getMessages,
|
|
|
|
|
setMessages,
|
|
|
|
|
setSiblingIdx,
|
|
|
|
|
latestMessage,
|
|
|
|
|
setLatestMessage,
|
|
|
|
|
resetLatestMessage,
|
|
|
|
|
ask,
|
|
|
|
|
index,
|
|
|
|
|
regenerate,
|
|
|
|
|
stopGenerating,
|
|
|
|
|
handleStopGenerating,
|
|
|
|
|
handleRegenerate,
|
|
|
|
|
handleContinue,
|
|
|
|
|
showPopover,
|
|
|
|
|
setShowPopover,
|
|
|
|
|
abortScroll,
|
|
|
|
|
setAbortScroll,
|
|
|
|
|
preset,
|
|
|
|
|
setPreset,
|
|
|
|
|
optionSettings,
|
|
|
|
|
setOptionSettings,
|
|
|
|
|
files,
|
|
|
|
|
setFiles,
|
|
|
|
|
filesLoading,
|
|
|
|
|
setFilesLoading,
|
|
|
|
|
};
|
|
|
|
|
}
|