impact-chatbot 2.3.19 → 2.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -23,7 +23,7 @@ import RefreshIcon from '@mui/icons-material/Refresh';
23
23
  import styled from 'styled-components';
24
24
  import { CircularProgress, Typography, Grid } from '@mui/material';
25
25
  import { fetchBaseUrl, replaceSpecialCharacter as replaceSpecialCharacter$1, fetchLegacyAgentScreen } from 'core/Utils/functions/utils';
26
- import { Button, Modal, AccordionModern, Tabs, Slider, Select, DatePicker, DateRangePicker, Checkbox, RadioButtonGroup, Input, Loader, ChatBotComponent } from 'impact-ui-v3';
26
+ import { Button, Modal, AccordionModern, Tabs, Slider, Select, DatePicker, DateRangePicker, Checkbox, RadioButtonGroup, Input, Loader, Tooltip, ChatBotComponent } from 'impact-ui-v3';
27
27
  import AgGridComponent from 'core/Utils/agGrid';
28
28
  import agGridColumnFormatter from 'core/Utils/agGrid/column-formatter';
29
29
  import CoreChart from 'core/Utils/core-charts';
@@ -32,6 +32,7 @@ import globalStyles$1 from 'core/Styles/globalStyles';
32
32
  import FormatListBulletedOutlinedIcon from '@mui/icons-material/FormatListBulletedOutlined';
33
33
  import PsychologyOutlinedIcon from '@mui/icons-material/PsychologyOutlined';
34
34
  import { stopAgentFlow } from 'core/commonComponents/smartBot/services/chatbot-services';
35
+ import SaveOutlinedIcon from '@mui/icons-material/SaveOutlined';
35
36
  import RangePicker from 'core/commonComponents/dateRangePicker';
36
37
 
37
38
  /**
@@ -592,7 +593,7 @@ const handleMessageLike = async (question, liked, setLoadingState, displaySnackM
592
593
  // question ===
593
594
  // `${item?.response_heading || item?.screen_name}_${item?.timeStamp}`
594
595
  // );
595
- const activeMessage = chatDataInfoRef?.[currentMode]?.conversations?.[1]?.messages?.[chatIndex];
596
+ const activeMessage = chatDataInfoRef?.[currentMode]?.conversations?.[activeConversationId]?.messages?.[chatIndex];
596
597
  // const activeMessage = chats?.[currentMode].conversations[activeConversationId].messages[activeMessageIndex];
597
598
  try {
598
599
  let request;
@@ -618,7 +619,7 @@ const handleMessageLike = async (question, liked, setLoadingState, displaySnackM
618
619
  // activeMessageIndex,
619
620
  // () => updatedMessage
620
621
  // );
621
- chatDataInfoRef[currentMode].conversations[1].messages[chatIndex] = updatedMessage;
622
+ chatDataInfoRef[currentMode].conversations[activeConversationId].messages[chatIndex] = updatedMessage;
622
623
  // templateData[currentMode].conversations[activeConversationId].messages = newChats;
623
624
  setChatDataState({ ...chatDataInfoRef });
624
625
  localStorage.setItem("chatData", JSON.stringify(templateData));
@@ -717,34 +718,35 @@ const getDynamicFunction = async (path, functionName) => {
717
718
  return null;
718
719
  }
719
720
  };
721
+ const generateConversationId = () => {
722
+ try {
723
+ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
724
+ }
725
+ catch (error) {
726
+ console.error("generateConversationId error", error);
727
+ return 0;
728
+ }
729
+ };
720
730
  /**
721
731
  * Generates a conversation object structure with empty messages array and current timestamp
722
732
  * @returns {object} - The conversation object structure
723
733
  */
724
- const generateConversationObject = () => {
734
+ const generateConversationObject = (conversationId) => {
725
735
  try {
726
736
  return {
727
- conversations: {
728
- 1: {
729
- id: 1,
730
- name: "Conversation 1",
731
- timestamp: new Date().toISOString(),
732
- messages: [],
733
- },
734
- },
737
+ id: conversationId,
738
+ name: `Conversation ${conversationId}`,
739
+ timestamp: new Date().toISOString(),
740
+ messages: [],
735
741
  };
736
742
  }
737
743
  catch (error) {
738
744
  console.error("generateConversationObject error", error);
739
745
  return {
740
- conversations: {
741
- 1: {
742
- id: 1,
743
- name: "Conversation 1",
744
- timestamp: new Date().toISOString(),
745
- messages: [],
746
- },
747
- },
746
+ id: conversationId,
747
+ name: `Conversation ${conversationId}`,
748
+ timestamp: new Date().toISOString(),
749
+ messages: [],
748
750
  };
749
751
  }
750
752
  };
@@ -941,6 +943,12 @@ const replaceSpecialCharToCharCode = (str) => {
941
943
  // Convert pixels to rem
942
944
  const pxToRem = (px) => `${px / 16}rem`;
943
945
 
946
+ // Get current user ID from session storage
947
+ const getCurrentUserId = () => {
948
+ const userDetails = JSON.parse(sessionStorage.getItem("userDetails") || "{}");
949
+ return userDetails?.user_id || null;
950
+ };
951
+
944
952
  // Get user name from session storage
945
953
  const getUserName = () => {
946
954
  const userDetails = JSON.parse(sessionStorage.getItem("userDetails") || "{}");
@@ -1190,7 +1198,9 @@ const ThinkinHeaderInfo = (props) => {
1190
1198
  // import { stackedBarChartExample } from "../examples/GraphExample";
1191
1199
  // import { examplePieChartData } from "../examples/GraphExample";
1192
1200
  const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, baseUrl = "", setCurrentSessionId = (params) => { }, customChatConfig = null, chatDataInfoRef = null, utilityObjectData = {}) => {
1193
- const setAgentFlow = useCallback(async (payload, input = "", baseUrlTemp = "") => {
1201
+ const { activeConversationId, setActiveConversationId } = utilityObjectData;
1202
+ const setAgentFlow = useCallback(async (payload, input = "", baseUrlTemp = "", conversationIdParam = null) => {
1203
+ let conversationId = conversationIdParam || activeConversationId;
1194
1204
  try {
1195
1205
  const currentTimeString = getCurrentDateTimeString(dateFormat);
1196
1206
  const currentModeValue = localStorage.getItem("currentModeData") || currentMode;
@@ -1208,17 +1218,24 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1208
1218
  timeStamp: currentTimeString,
1209
1219
  userType: "loader",
1210
1220
  };
1211
- if (isEmpty(chatDataInfoRef.current[currentModeValue])) {
1212
- chatDataInfoRef.current[currentModeValue] = generateConversationObject();
1213
- }
1221
+ if (!conversationId || isEmpty(chatDataInfoRef.current[currentModeValue].conversations[conversationId])) {
1222
+ conversationId = generateConversationId();
1223
+ setActiveConversationId(conversationId);
1224
+ chatDataInfoRef.current[currentModeValue].conversations[conversationId] = generateConversationObject(conversationId);
1225
+ }
1226
+ // if (isEmpty(chatDataInfoRef.current[currentModeValue])) {
1227
+ // chatDataInfoRef.current[
1228
+ // currentModeValue
1229
+ // ] = generateConversationObject();
1230
+ // }
1214
1231
  if (showUserChat) {
1215
1232
  chatDataRef.current[currentModeValue] = [
1216
1233
  ...chatDataRef.current?.[currentModeValue],
1217
1234
  userChat,
1218
1235
  loaderData,
1219
1236
  ];
1220
- chatDataInfoRef.current[currentModeValue].conversations[1].messages = [
1221
- ...chatDataInfoRef.current[currentModeValue].conversations[1]
1237
+ chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages = [
1238
+ ...chatDataInfoRef.current[currentModeValue].conversations[conversationId]
1222
1239
  .messages,
1223
1240
  userChat,
1224
1241
  ];
@@ -1236,7 +1253,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1236
1253
  let response = {};
1237
1254
  if (utilityObjectData?.runStreaming) {
1238
1255
  let utilityObject = {
1239
- activeConversationId: utilityObjectData?.activeConversationId,
1256
+ activeConversationId: conversationId,
1240
1257
  currentMode: currentModeValue,
1241
1258
  chatDataRef,
1242
1259
  chatBodyRef: utilityObjectData?.chatBodyRef,
@@ -1275,9 +1292,9 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1275
1292
  baseUrl: baseUrlTemp,
1276
1293
  };
1277
1294
  response = await parseResponse(null, "stream", "", currentModeValue, false, "", {}, payload, utilityObject);
1278
- let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[1].messages;
1295
+ let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages;
1279
1296
  chatDataMessages = [...chatDataMessages, response];
1280
- chatDataInfoRef.current[currentModeValue].conversations[1].messages = chatDataMessages;
1297
+ chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages = chatDataMessages;
1281
1298
  // Trigger re-render by updating chatDataState
1282
1299
  if (utilityObjectData?.setChatDataState) {
1283
1300
  utilityObjectData.setChatDataState({ ...chatDataRef.current });
@@ -1609,7 +1626,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1609
1626
  // data: tableResponse,
1610
1627
  // },
1611
1628
  // };
1612
- processResponse(response, payload, currentModeValue, customChatConfig);
1629
+ processResponse(response, payload, currentModeValue, customChatConfig, {}, conversationId);
1613
1630
  // let parsedResponse = {};
1614
1631
  // let customParseResponse = null;
1615
1632
  // // Check if a custom parser is provided and load it
@@ -1772,9 +1789,9 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1772
1789
  bodyType: "text",
1773
1790
  };
1774
1791
  const currentModeValue = localStorage.getItem("currentModeData") || currentMode;
1775
- let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[1].messages;
1792
+ let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages;
1776
1793
  chatDataMessages = [...chatDataMessages, failResponseText];
1777
- chatDataInfoRef.current[currentModeValue].conversations[1].messages = chatDataMessages;
1794
+ chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages = chatDataMessages;
1778
1795
  chatDataRef.current[currentMode] = [
1779
1796
  ...chatDataRef.current[currentMode]?.filter((data) => data.userType !== "loader"),
1780
1797
  failResponseText,
@@ -1785,7 +1802,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1785
1802
  }
1786
1803
  setLoader(false);
1787
1804
  }
1788
- }, [currentMode, chatDataRef, baseUrl, customChatConfig, utilityObjectData?.thinkingContent]);
1805
+ }, [currentMode, chatDataRef, baseUrl, customChatConfig, utilityObjectData?.thinkingContent, activeConversationId]);
1789
1806
  const prepareDataAndSendToAgent = useCallback((data, init = false, utilityObjectData) => {
1790
1807
  try {
1791
1808
  let payload = {};
@@ -1829,13 +1846,15 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1829
1846
  }
1830
1847
  dispatch(setChatbotContext({}));
1831
1848
  }
1832
- setAgentFlow(payload, "", data?.baseUrl);
1849
+ // Get activeConversationId from utilityObjectData if available, otherwise use the one from closure
1850
+ const currentConversationId = utilityObjectData?.activeConversationId || activeConversationId;
1851
+ setAgentFlow(payload, "", data?.baseUrl, currentConversationId);
1833
1852
  }
1834
1853
  catch (error) {
1835
1854
  console.error("Error in prepareDataAndSendToAgent: ", error);
1836
1855
  }
1837
- }, []);
1838
- const processResponse = useCallback(async (response, payload, currentModeValue, customChatConfig, utilsObject) => {
1856
+ }, [activeConversationId, setAgentFlow]);
1857
+ const processResponse = useCallback(async (response, payload, currentModeValue, customChatConfig, utilsObject, conversationId) => {
1839
1858
  try {
1840
1859
  let parsedResponse = {};
1841
1860
  let customParseResponse = null;
@@ -1937,7 +1956,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1937
1956
  if (utilsObject?.newChatData) {
1938
1957
  chatDataInfoRef.current = utilsObject?.newChatData.current;
1939
1958
  }
1940
- let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[1].messages;
1959
+ let chatDataMessages = chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages;
1941
1960
  let finalParsedResponse = isArray(parsedResponse)
1942
1961
  ? parsedResponse
1943
1962
  : [parsedResponse];
@@ -1945,7 +1964,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1945
1964
  message.firstMessage = index === 0 ? true : false;
1946
1965
  });
1947
1966
  chatDataMessages = [...chatDataMessages, ...(Array.isArray(finalParsedResponse) ? finalParsedResponse : [])];
1948
- chatDataInfoRef.current[currentModeValue].conversations[1].messages = chatDataMessages;
1967
+ chatDataInfoRef.current[currentModeValue].conversations[conversationId].messages = chatDataMessages;
1949
1968
  // Trigger re-render by updating chatDataState
1950
1969
  if (utilityObjectData?.setChatDataState) {
1951
1970
  utilityObjectData.setChatDataState({ ...chatDataRef.current });
@@ -1965,7 +1984,7 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
1965
1984
  };
1966
1985
  };
1967
1986
 
1968
- const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUserInput, setQuestionIndex, setCurrentAppLink, flowType, screenName, questionIndex, userInput, dateFormat, currentMode, activeConversationId, setIsModuleChanged, chatBodyRef, filterReducerState, dispatch, navigate, setShowChatPlaceholder, baseUrl, setChatDataState, setCurrentSessionId, customChatConfig, chatDataInfoRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, initValue, sessionId, fieldNumber, setFieldNumber, additionalArgs) => {
1987
+ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUserInput, setQuestionIndex, setCurrentAppLink, flowType, screenName, questionIndex, userInput, dateFormat, currentMode, activeConversationId, setIsModuleChanged, chatBodyRef, filterReducerState, dispatch, navigate, setShowChatPlaceholder, baseUrl, setChatDataState, setCurrentSessionId, customChatConfig, chatDataInfoRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, initValue, sessionId, fieldNumber, setFieldNumber, additionalArgs, setActiveConversationId) => {
1969
1988
  const { prepareDataAndSendToAgent, setAgentFlow, processResponse, } = useAgentFlow(dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, baseUrl, setCurrentSessionId, customChatConfig, chatDataInfoRef, {
1970
1989
  setChatDataState,
1971
1990
  activeConversationId,
@@ -2161,12 +2180,11 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2161
2180
  setUserInput(data.displayText);
2162
2181
  }
2163
2182
  else {
2164
- fetchUserResultsFromQuery(data, true);
2183
+ fetchUserResultsFromQuery(data, true, "", activeConversationId);
2165
2184
  }
2166
2185
  }, [activeConversationId, baseUrl]);
2167
- const fetchUserResultsFromQuery = useCallback(async (refObject, fetchQuestions = false, inputValue = userInput) => {
2186
+ const fetchUserResultsFromQuery = useCallback(async (refObject, fetchQuestions = false, inputValue = userInput, conversationId = activeConversationId) => {
2168
2187
  let flowType = refObject?.flow_type ? refObject?.flow_type : currentMode;
2169
- ensureConversationExists(flowType, activeConversationId, chatDataRef);
2170
2188
  const currentTimeString = getCurrentDateTimeString();
2171
2189
  const input = fetchQuestions ? refObject?.screen_name : inputValue;
2172
2190
  setUserInput("");
@@ -2183,16 +2201,21 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2183
2201
  timeStamp: currentTimeString,
2184
2202
  userType: "loader",
2185
2203
  };
2186
- if (isEmpty$1(chatDataInfoRef.current[currentMode])) {
2187
- chatDataInfoRef.current[currentMode] = generateConversationObject();
2188
- }
2189
- chatDataRef.current[flowType].conversations[activeConversationId].messages = [
2190
- ...chatDataRef.current[flowType].conversations[activeConversationId].messages,
2204
+ if (!conversationId || isEmpty$1(chatDataInfoRef.current[currentMode].conversations[conversationId])) {
2205
+ conversationId = generateConversationId();
2206
+ setActiveConversationId(conversationId);
2207
+ chatDataInfoRef.current[currentMode].conversations[conversationId] = generateConversationObject(conversationId);
2208
+ }
2209
+ // Ensure chatDataRef conversation entry exists for the (potentially new) conversationId.
2210
+ // Must be called AFTER the ID check above so it uses the correct ID.
2211
+ ensureConversationExists(flowType, conversationId, chatDataRef);
2212
+ chatDataRef.current[flowType].conversations[conversationId].messages = [
2213
+ ...chatDataRef.current[flowType].conversations[conversationId].messages,
2191
2214
  userChat,
2192
2215
  loaderData,
2193
2216
  ];
2194
- chatDataInfoRef.current[currentMode].conversations[1].messages = [
2195
- ...chatDataInfoRef.current[currentMode].conversations[1].messages,
2217
+ chatDataInfoRef.current[currentMode].conversations[conversationId].messages = [
2218
+ ...chatDataInfoRef.current[currentMode].conversations[conversationId].messages,
2196
2219
  userChat,
2197
2220
  ];
2198
2221
  setLoader(true);
@@ -2215,13 +2238,13 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2215
2238
  // );
2216
2239
  getUpdatedChat = parseResponse({ ...queryResponse?.data?.data }, "questions");
2217
2240
  }
2218
- chatDataRef.current[flowType].conversations[activeConversationId].messages = [
2219
- ...chatDataRef.current[flowType].conversations[activeConversationId].messages?.filter((data) => data?.userType !== "loader"),
2241
+ chatDataRef.current[flowType].conversations[conversationId].messages = [
2242
+ ...chatDataRef.current[flowType].conversations[conversationId].messages?.filter((data) => data?.userType !== "loader"),
2220
2243
  getUpdatedChat,
2221
2244
  ];
2222
- let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[1].messages;
2245
+ let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[conversationId].messages;
2223
2246
  chatDataMessages = [...chatDataMessages, getUpdatedChat];
2224
- chatDataInfoRef.current[currentMode].conversations[1].messages = chatDataMessages;
2247
+ chatDataInfoRef.current[currentMode].conversations[conversationId].messages = chatDataMessages;
2225
2248
  // Trigger re-render by updating chatDataState
2226
2249
  setChatDataState({ ...chatDataRef.current });
2227
2250
  }
@@ -2240,7 +2263,7 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2240
2263
  };
2241
2264
  }
2242
2265
  let utitlityObject = {
2243
- activeConversationId,
2266
+ activeConversationId: conversationId,
2244
2267
  currentMode,
2245
2268
  chatDataRef,
2246
2269
  chatBodyRef,
@@ -2277,13 +2300,13 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2277
2300
  getUpdatedChat = parseResponse({ ...responseData, enableLikes: true }, "text");
2278
2301
  }
2279
2302
  }
2280
- chatDataRef.current[currentMode].conversations[activeConversationId].messages = [
2281
- ...chatDataRef.current[currentMode].conversations[activeConversationId].messages?.filter((data) => data?.userType !== "loader"),
2303
+ chatDataRef.current[currentMode].conversations[conversationId].messages = [
2304
+ ...chatDataRef.current[currentMode].conversations[conversationId].messages?.filter((data) => data?.userType !== "loader"),
2282
2305
  getUpdatedChat,
2283
2306
  ];
2284
- let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[1].messages;
2307
+ let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[conversationId].messages;
2285
2308
  chatDataMessages = [...chatDataMessages, getUpdatedChat];
2286
- chatDataInfoRef.current[currentMode].conversations[1].messages = chatDataMessages;
2309
+ chatDataInfoRef.current[currentMode].conversations[conversationId].messages = chatDataMessages;
2287
2310
  }
2288
2311
  setChatDataState({ ...chatDataRef.current });
2289
2312
  setLoader(false);
@@ -2300,13 +2323,13 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
2300
2323
  noShowHeaderTitle: true,
2301
2324
  bodyType: "text",
2302
2325
  };
2303
- chatDataRef.current[currentMode].conversations[activeConversationId].messages = [
2304
- ...chatDataRef.current[currentMode].conversations[activeConversationId].messages?.filter((data) => data.userType !== "loader"),
2326
+ chatDataRef.current[currentMode].conversations[conversationId].messages = [
2327
+ ...chatDataRef.current[currentMode].conversations[conversationId].messages?.filter((data) => data.userType !== "loader"),
2305
2328
  failResponseText,
2306
2329
  ];
2307
- let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[1].messages;
2330
+ let chatDataMessages = chatDataInfoRef.current[currentMode].conversations[conversationId].messages;
2308
2331
  chatDataMessages = [...chatDataMessages, failResponseText];
2309
- chatDataInfoRef.current[currentMode].conversations[1].messages = chatDataMessages;
2332
+ chatDataInfoRef.current[currentMode].conversations[conversationId].messages = chatDataMessages;
2310
2333
  // Trigger re-render by updating chatDataState
2311
2334
  setChatDataState({ ...chatDataRef.current });
2312
2335
  setLoader(false);
@@ -2495,7 +2518,7 @@ const useChatSession = (chatDataRef, setFlowType, setScreenName, setUserInput, s
2495
2518
  let chatDataInfo = cloneDeep(chatDataRef.current);
2496
2519
  delete chatDataInfo.agent;
2497
2520
  for (const property in chatDataInfo) {
2498
- if (isEmpty$1(chatDataRef.current[property].conversations)) {
2521
+ if (isEmpty$1(chatDataRef.current[property].conversations) || !chatDataRef.current[property].conversations[activeConversationId]) {
2499
2522
  ensureConversationExists(property, activeConversationId, chatDataRef);
2500
2523
  }
2501
2524
  }
@@ -3950,8 +3973,12 @@ const useChatState = () => {
3950
3973
  });
3951
3974
  const chatDataInfoRef = useRef({
3952
3975
  insights: {},
3953
- navigation: {},
3954
- agent: {}
3976
+ navigation: {
3977
+ conversations: {},
3978
+ },
3979
+ agent: {
3980
+ conversations: {},
3981
+ }
3955
3982
  });
3956
3983
  const chatBodyRef = useRef({});
3957
3984
  const isDraggingRef = useRef(null);
@@ -4534,7 +4561,7 @@ const Rectangle = ({ type, icon, title, description, onClick, hoverable }) => {
4534
4561
  return (jsx("div", { className: `${classes.rectangle} ${classes[type]} ${hoverable ? classes.rectangleHoverable : ''}`, onClick: onClick, title: isTruncated ? title : null, children: jsxs("div", { className: classes.textContainer, children: [jsx(Typography, { className: classes.title, ref: titleRef, children: title }), jsx(Typography, { className: classes.description, children: description })] }) }));
4535
4562
  };
4536
4563
  const ChatPlaceholder = (props) => {
4537
- const { dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, setCurrentAgentId, baseUrl, setBaseUrl, setCurrentSessionId, customChatConfig, chatDataInfoRef, setChatDataState, userInput, legacyAgentScreen, activeConversationId, chatBodyRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, setUniqueChatId, fieldNumber, setFieldNumber, setAdditionalArgs, questions, displayQuestions } = props;
4564
+ const { dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, setCurrentAgentId, baseUrl, setBaseUrl, setCurrentSessionId, customChatConfig, chatDataInfoRef, setChatDataState, userInput, legacyAgentScreen, activeConversationId, chatBodyRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, setUniqueChatId, fieldNumber, setFieldNumber, setAdditionalArgs, questions, displayQuestions, setActiveConversationId } = props;
4538
4565
  const classes = useStyles$5();
4539
4566
  globalStyles();
4540
4567
  const [cardList, setCardList] = useState([]);
@@ -4565,6 +4592,7 @@ const ChatPlaceholder = (props) => {
4565
4592
  fieldNumber,
4566
4593
  setFieldNumber,
4567
4594
  setAdditionalArgs,
4595
+ setActiveConversationId
4568
4596
  });
4569
4597
  const getBaseUrl = async () => {
4570
4598
  try {
@@ -5963,7 +5991,7 @@ const formatThinkingTime = (seconds) => {
5963
5991
  * @param {Function} botData.utilityObject.setChatDataState - Function to update chat data state
5964
5992
  */
5965
5993
  const StreamedContent = ({ botData }) => {
5966
- const { activeConversationId, currentMode, chatDataRef, chatBodyRef, setChatDataState, chatDataInfoRef, setLoader = (params) => { }, processResponse = (params) => { }, setThinkingContent, thinkingContent, isThinking: isThinkingFromParent, setIsThinking: setIsThinkingFromParent, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, baseUrl } = botData.utilityObject;
5994
+ const { activeConversationId, currentMode, chatDataRef, chatBodyRef, setChatDataState, chatDataInfoRef, setLoader = (params) => { }, processResponse = (params) => { }, setThinkingContent, thinkingContent, isThinking: isThinkingFromParent, setIsThinking: setIsThinkingFromParent, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, baseUrl } = botData.utilityObject || {};
5967
5995
  const classes = useStyles$3();
5968
5996
  useStyles$6();
5969
5997
  const dispatch = useDispatch();
@@ -6337,8 +6365,8 @@ const StreamedContent = ({ botData }) => {
6337
6365
  chatDataRef.current[currentMode] = [
6338
6366
  ...chatDataRef.current[currentMode].slice(0, -1),
6339
6367
  ];
6340
- chatDataInfoRef.current[currentMode].conversations[1].messages = [
6341
- ...chatDataInfoRef.current[currentMode].conversations[1].messages.slice(0, -1),
6368
+ chatDataInfoRef.current[currentMode].conversations[activeConversationId].messages = [
6369
+ ...chatDataInfoRef.current[currentMode].conversations[activeConversationId].messages.slice(0, -1),
6342
6370
  ];
6343
6371
  botData.utilityObject.setInitValue(messageToStoreRef.current.initValue);
6344
6372
  botData.utilityObject.setSessionId(messageToStoreRef.current.sessionId);
@@ -6404,7 +6432,7 @@ const StreamedContent = ({ botData }) => {
6404
6432
  currentTabValue: "agent_response",
6405
6433
  questions: cloneDeep(questionsRef.current),
6406
6434
  questionsStepsMap: cloneDeep(questionsStepsMapRef.current),
6407
- });
6435
+ }, activeConversationId);
6408
6436
  // [
6409
6437
  // {
6410
6438
  // header: "Finding relevant information",
@@ -6454,13 +6482,15 @@ const StreamedContent = ({ botData }) => {
6454
6482
  // // enableLikes: true
6455
6483
  // },
6456
6484
  ];
6457
- chatDataInfoRef.current[currentMode].conversations[1].messages = [
6458
- ...chatDataInfoRef.current[currentMode].conversations[1].messages.slice(0, -1),
6459
- // {
6460
- // ...parsedResponse,
6461
- // // enableLikes: true
6462
- // },
6463
- ];
6485
+ if (chatDataInfoRef.current[currentMode]?.conversations?.[activeConversationId]) {
6486
+ chatDataInfoRef.current[currentMode].conversations[activeConversationId].messages = [
6487
+ ...chatDataInfoRef.current[currentMode].conversations?.[activeConversationId]?.messages?.slice(0, -1),
6488
+ // {
6489
+ // ...parsedResponse,
6490
+ // // enableLikes: true
6491
+ // },
6492
+ ];
6493
+ }
6464
6494
  let finalData = isArray(messageToStoreRef?.current?.appendedData)
6465
6495
  ? messageToStoreRef?.current?.appendedData
6466
6496
  : isEmpty(messageToStoreRef?.current?.appendedData)
@@ -6484,7 +6514,7 @@ const StreamedContent = ({ botData }) => {
6484
6514
  currentTabValue: "agent_response",
6485
6515
  questions: cloneDeep(questionsRef.current),
6486
6516
  questionsStepsMap: cloneDeep(questionsStepsMapRef.current),
6487
- });
6517
+ }, activeConversationId);
6488
6518
  }
6489
6519
  // Clean up module-level Map entry - stream is fully processed
6490
6520
  streamStateMap.delete(streamKey);
@@ -6493,7 +6523,7 @@ const StreamedContent = ({ botData }) => {
6493
6523
  setChatDataState({ ...chatDataRef.current });
6494
6524
  }, 1000);
6495
6525
  }
6496
- }, [isStreamingDone, thinkingTime]);
6526
+ }, [isStreamingDone, thinkingTime, activeConversationId]);
6497
6527
  useEffect(() => {
6498
6528
  if (currentMode === "agent") {
6499
6529
  if (sourceRef.current && isStreaming) {
@@ -8499,7 +8529,7 @@ const useMentionState = () => {
8499
8529
  };
8500
8530
 
8501
8531
  const ChatbotInput = (props) => {
8502
- const { newChatScreen, inputValue, setInputValue, isStopIcon, handleMicClick, handleRefresh, onSendIconClick, onStopIconClick, currentMode, filterOptions, } = props;
8532
+ const { newChatScreen, inputValue, setInputValue, isStopIcon, handleMicClick, handleRefresh, onSendIconClick, onStopIconClick, currentMode, filterOptions, onSaveClick, } = props;
8503
8533
  const editorRef = useRef(null);
8504
8534
  const selectRef = useRef(null);
8505
8535
  const dateRangePickerRef = useRef(null);
@@ -9809,7 +9839,9 @@ const ChatbotInput = (props) => {
9809
9839
  // disableType="disableOnlyPast"
9810
9840
  , {
9811
9841
  // disableType="disableOnlyPast"
9812
- startDate: dateRangeStartDate, endDate: dateRangeEndDate, focusedInput: dateRangeFocusedInput, onDatesChange: handleDateRangeChange, onFocusChange: setDateRangeFocusedInput }) })), jsxs("div", { className: `chat-actions ${isFixed ? "fixed" : ""}`, children: [handleRefresh && (jsx(Button, { icon: jsx(SvgChatBotRefreshIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "url", onClick: handleRefresh })), handleMicClick && (jsx(Button, { icon: jsx(SvgChatBotMicIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "tertiary", onClick: handleMicClick })), jsx(Button, { icon: !isStopIcon ? jsx(SvgChatBotSendIcon, {}) : jsx(SvgChatbotStopIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "primary", onClick: !isStopIcon ? handleSendMessage : onStopIconClick, id: "chat-input-send-button", className: isStopIcon ? "stop-icon-button" : "" })] })] }) }));
9842
+ startDate: dateRangeStartDate, endDate: dateRangeEndDate, focusedInput: dateRangeFocusedInput, onDatesChange: handleDateRangeChange, onFocusChange: setDateRangeFocusedInput }) })), jsxs("div", { className: `chat-actions ${isFixed ? "fixed" : ""}`, children: [handleRefresh && (jsx(Button, { icon: jsx(SvgChatBotRefreshIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "url", onClick: handleRefresh })), handleMicClick && (jsx(Button, { icon: jsx(SvgChatBotMicIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "tertiary", onClick: handleMicClick })), onSaveClick && (jsx(Tooltip, { title: "Save Chat", children: jsx(Button, { icon: jsx(SaveOutlinedIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "tertiary", onClick: onSaveClick, id: "chat-input-save-button" }) })), jsx(Button, { icon: !isStopIcon ? jsx(SvgChatBotSendIcon, {}) : jsx(SvgChatbotStopIcon, {}), iconPlacement: "left", size: "large", type: "default", variant: "primary", onClick: () => {
9843
+ !isStopIcon ? handleSendMessage() : onStopIconClick();
9844
+ }, id: "chat-input-send-button", className: isStopIcon ? "stop-icon-button" : "" })] })] }) }));
9813
9845
  };
9814
9846
 
9815
9847
  let chatbotFilterCustomConfig = {
@@ -9886,6 +9918,519 @@ let chatbotFilterCustomConfig = {
9886
9918
  sub_offset: null,
9887
9919
  download_rows: null,
9888
9920
  };
9921
+ let singleConversationNewData = [
9922
+ {
9923
+ userType: "user",
9924
+ chatType: "text",
9925
+ data: "List the products which are about to change status in next 10 days",
9926
+ },
9927
+ {
9928
+ userType: "bot",
9929
+ chatType: "thinking",
9930
+ data: "I will fetch all product status records with effective date ranges that begin or end within the next 10 days. This will provide the raw data needed to identify which products are about to change their active/inactive status soon. Downstream nodes will filter and compute which products have a status transition in the specified window, ensuring the user receives a list of products with upcoming status changes.I will fetch all product status records with effective date ranges that begin or end within the next 10 days. This will provide the raw data needed to identify which products are about to change their active/inactive status soon. Downstream nodes will filter and compute which products have a status transition in the specified window, ensuring the user receives a list of products with upcoming status changes.",
9931
+ },
9932
+ {
9933
+ userType: "bot",
9934
+ chatType: "steps",
9935
+ data: [
9936
+ {
9937
+ header: "Assessing user query",
9938
+ step_status: "completed",
9939
+ sub_header: "Query is within scope and determined as New query",
9940
+ current_intent: "List the products which are about to change status in next 10 days"
9941
+ },
9942
+ {
9943
+ header: "Creating Plan of Action",
9944
+ step_status: "completed",
9945
+ sub_header: "Alan is working to determine the best approach to answer user query",
9946
+ current_intent: "List the products which are about to change status in next 10 days"
9947
+ },
9948
+ {
9949
+ header: "Executing Step",
9950
+ step_status: "completed",
9951
+ sub_header: "Executing Step 1/1",
9952
+ current_intent: "List the products which are about to change status in next 10 days"
9953
+ },
9954
+ ]
9955
+ },
9956
+ {
9957
+ userType: "bot",
9958
+ chatType: "agent",
9959
+ data: [
9960
+ { "type": "select", "data": { "header": "Select", "inputPosition": "inline", "labelOrientation": "top", "label": "L0 Name", "param_name": "l0_name", "options": [{ "label": "Coach", "value": "Coach" }, { "label": "KateSpade", "value": "KateSpade" }], "isRequired": true, "isDisabled": false, "isMulti": true } }, { "type": "select", "data": { "header": "Select", "inputPosition": "inline", "labelOrientation": "top", "label": "L1 Name", "param_name": "l1_name", "options": [{ "label": "Outlet-Store", "value": "Outlet-Store" }, { "label": "Retail-Store", "value": "Retail-Store" }], "isRequired": true, "isDisabled": false, "isMulti": true } }, { "type": "table", "data": { "display_name": "Results", "unique_id": "", "row_data": [{ "Style Color ID": "CDM80 B4__ia_char_03M2-Retail-Store", "Style Description": "DSNY GLOV SWINGER", "stockout_store_count": 346, "max_dc_oh_it_oo": 284.0, "lw_sales_units": 6 }, { "Style Color ID": "CDN03 B4PF7-Retail-Store", "Style Description": "DSNY GLOV SWINGER", "stockout_store_count": 346, "max_dc_oh_it_oo": 274.0, "lw_sales_units": 5 }, { "Style Color ID": "CT255 IMWQJ-Retail-Store", "Style Description": "LTH STP JAMIE CMR", "stockout_store_count": 346, "max_dc_oh_it_oo": 13.0, "lw_sales_units": 2 }, { "Style Color ID": "CZ186 IMY4C-Retail-Store", "Style Description": "SIG JAMIE CMR", "stockout_store_count": 346, "max_dc_oh_it_oo": 6.0, "lw_sales_units": 1 }, { "Style Color ID": "CCZ17 IMA47-Retail-Store", "Style Description": "CHRRY PT RWN BKT", "stockout_store_count": 346, "max_dc_oh_it_oo": 4.0, "lw_sales_units": 1 }], "table_config": [{ "column_header": "Style Color Id", "field": "Style Color ID", "is_searchable": true, "type": "str" }, { "column_header": "Style Description", "field": "Style Description", "is_searchable": true }, { "column_header": "Stockout Store Count", "field": "stockout_store_count", "is_searchable": true }, { "column_header": "Max Dc Oh It Oo", "field": "max_dc_oh_it_oo", "is_searchable": true }, { "column_header": "Lw Sales Units", "field": "lw_sales_units", "is_searchable": true }] } }
9961
+ ]
9962
+ }
9963
+ ];
9964
+
9965
+ const fetchConversations = async (currentMode) => {
9966
+ try {
9967
+ // Will be replaced with actual API call
9968
+ return axiosInstance({
9969
+ url: `core/chatbot/conversation/${currentMode}`,
9970
+ method: "GET"
9971
+ });
9972
+ // return {
9973
+ // status: true,
9974
+ // data: {
9975
+ // data: [
9976
+ // {
9977
+ // conversation_id: 10,
9978
+ // module_name: moduleType.toUpperCase(),
9979
+ // flow_type: moduleType.toUpperCase(),
9980
+ // name: "test chatbot's name",
9981
+ // created_at: new Date().toISOString(),
9982
+ // updated_at: new Date().toISOString(),
9983
+ // }
9984
+ // ]
9985
+ // }
9986
+ // };
9987
+ }
9988
+ catch (error) {
9989
+ console.error("fetchConversations error", error);
9990
+ return null;
9991
+ }
9992
+ };
9993
+ const createConversation = async (payload) => {
9994
+ try {
9995
+ return axiosInstance({
9996
+ url: `core/chatbot/conversation`,
9997
+ method: "POST",
9998
+ data: payload
9999
+ });
10000
+ }
10001
+ catch (error) {
10002
+ console.error("createConversation error", error);
10003
+ return null;
10004
+ }
10005
+ };
10006
+ const updateConversation = async (conversationId, payload) => {
10007
+ try {
10008
+ return axiosInstance({
10009
+ url: `core/chatbot/conversation/update`,
10010
+ method: "POST",
10011
+ data: payload
10012
+ });
10013
+ }
10014
+ catch (error) {
10015
+ console.error("updateConversation error", error);
10016
+ return null;
10017
+ }
10018
+ };
10019
+ const deleteConversation = async (conversationId) => {
10020
+ try {
10021
+ return axiosInstance({
10022
+ url: `core/chatbot/conversation/${conversationId}`,
10023
+ method: "DELETE"
10024
+ });
10025
+ }
10026
+ catch (error) {
10027
+ console.error("deleteConversation error", error);
10028
+ return null;
10029
+ }
10030
+ };
10031
+ const saveChat = async (payload) => {
10032
+ try {
10033
+ return axiosInstance({
10034
+ url: `core/chatbot/conversation`,
10035
+ method: "POST",
10036
+ data: payload
10037
+ });
10038
+ }
10039
+ catch (error) {
10040
+ console.error("saveChat error", error);
10041
+ return null;
10042
+ }
10043
+ };
10044
+
10045
+ const useConversationManagement = (chatDataRef, currentMode, activeConversationId, setActiveConversationId, setChatDataState, selectedModule, setSelectedModule, isModuleChanged, setIsModuleChanged, setActiveChatId = () => { }, saveCurrentChanges = () => { }, chatDataInfoRef = null, setHistoryPanelData = (_data) => { }, processResponse = null) => {
10046
+ const [loading, setLoading] = useState(false);
10047
+ const [error, setError] = useState(null);
10048
+ const fetchConversations$1 = useCallback(async (activeChatId = null, mode = null) => {
10049
+ try {
10050
+ setLoading(true);
10051
+ const effectiveMode = mode || currentMode;
10052
+ const response = await fetchConversations(effectiveMode);
10053
+ // const response = {
10054
+ // status: true,
10055
+ // data: {
10056
+ // data: [
10057
+ // {
10058
+ // conversation_id: 1,
10059
+ // name: "Getting Started Guide",
10060
+ // created_at: new Date().toISOString(),
10061
+ // updated_at: new Date().toISOString(),
10062
+ // },
10063
+ // {
10064
+ // conversation_id: 2,
10065
+ // name: "Product Features Discussion",
10066
+ // created_at: new Date(Date.now() - 86400000).toISOString(), // 1 day ago
10067
+ // updated_at: new Date(Date.now() - 86400000).toISOString(),
10068
+ // },
10069
+ // {
10070
+ // conversation_id: 3,
10071
+ // name: "Troubleshooting Help",
10072
+ // created_at: new Date(Date.now() - 172800000).toISOString(), // 2 days ago
10073
+ // updated_at: new Date(Date.now() - 172800000).toISOString(),
10074
+ // },
10075
+ // {
10076
+ // conversation_id: 4,
10077
+ // name: "Project Discussion",
10078
+ // created_at: new Date(Date.now() - 948220200000).toISOString(), // 2 days ago
10079
+ // updated_at: new Date(Date.now() - 948220200000).toISOString(),
10080
+ // },
10081
+ // ],
10082
+ // },
10083
+ // };
10084
+ if (response?.data?.status) {
10085
+ const conversationsList = response.data.data.data;
10086
+ chatDataRef.current[effectiveMode].conversationsList = conversationsList;
10087
+ // Process conversations from each time group
10088
+ conversationsList.forEach(group => {
10089
+ group.conversation_list.forEach(conversation => {
10090
+ // chatDataRef.current[currentMode].conversations[conversation.conversation_id] = {
10091
+ // id: conversation.conversation_id,
10092
+ // name: conversation.name,
10093
+ // idGenerated: true,
10094
+ // timestamp: conversation.created_at || new Date().toISOString(),
10095
+ // messages: []
10096
+ // };
10097
+ if (chatDataInfoRef?.current[effectiveMode]?.conversations?.[conversation.conversation_id]?.messages) {
10098
+ chatDataInfoRef.current[effectiveMode].conversations[conversation.conversation_id] = {
10099
+ id: conversation.conversation_id,
10100
+ name: conversation.name,
10101
+ idGenerated: true,
10102
+ timestamp: conversation.created_at || new Date().toISOString(),
10103
+ messages: chatDataInfoRef.current[effectiveMode].conversations[conversation.conversation_id].messages
10104
+ };
10105
+ }
10106
+ });
10107
+ });
10108
+ setHistoryPanelData(conversationsList);
10109
+ setChatDataState({ ...chatDataRef.current });
10110
+ if (activeChatId) {
10111
+ setActiveChatId(activeChatId);
10112
+ }
10113
+ // Set first conversation as active if none selected
10114
+ // if (!activeConversationId && Object.keys(conversations).length > 0) {
10115
+ // setActiveConversationId(Object.keys(conversations)[0]);
10116
+ // }
10117
+ }
10118
+ }
10119
+ catch (err) {
10120
+ setError(err.message);
10121
+ }
10122
+ finally {
10123
+ setLoading(false);
10124
+ }
10125
+ }, [currentMode]);
10126
+ const fetchConversationChats = useCallback(async (conversationId, mode = null) => {
10127
+ const effectiveMode = mode || currentMode;
10128
+ try {
10129
+ setLoading(true);
10130
+ // --- Use hardcoded test data for now ---
10131
+ const savedData = singleConversationNewData;
10132
+ // Generate a conversation ID for the saved chat
10133
+ const savedConvId = conversationId || generateConversationId();
10134
+ // Ensure a conversation slot exists in chatDataInfoRef
10135
+ if (chatDataInfoRef) {
10136
+ if (!chatDataInfoRef.current[effectiveMode]?.conversations) {
10137
+ chatDataInfoRef.current[effectiveMode] = { conversations: {} };
10138
+ }
10139
+ chatDataInfoRef.current[effectiveMode].conversations[savedConvId] =
10140
+ generateConversationObject(savedConvId);
10141
+ }
10142
+ setActiveConversationId(savedConvId);
10143
+ // Build combined bot entries from the saved data
10144
+ // Collect thinking, steps, and agent response into a single combined message
10145
+ let thinkingResponse = {};
10146
+ let steps = [];
10147
+ const agentDataItems = [];
10148
+ let userMessage = null;
10149
+ savedData.forEach((item) => {
10150
+ if (item.userType === "user") {
10151
+ userMessage = {
10152
+ timeStamp: moment().format("DD-MM-YYYY HH:mm:ss"),
10153
+ userType: "user",
10154
+ bodyText: item.data,
10155
+ bodyType: "text",
10156
+ };
10157
+ }
10158
+ else if (item.chatType === "thinking") {
10159
+ thinkingResponse = {
10160
+ thinkingStream: item.data,
10161
+ thinkingContent: item.data,
10162
+ thinkingTime: 1,
10163
+ thinkingHeading: "Thinking Completed",
10164
+ };
10165
+ }
10166
+ else if (item.chatType === "steps") {
10167
+ steps = item.data;
10168
+ }
10169
+ else if (item.chatType === "agent") {
10170
+ // Agent response items (widgets, selects, etc.)
10171
+ if (Array.isArray(item.data)) {
10172
+ agentDataItems.push(...item.data);
10173
+ }
10174
+ else {
10175
+ agentDataItems.push(item.data);
10176
+ }
10177
+ }
10178
+ });
10179
+ // Add user message to conversation
10180
+ if (userMessage && chatDataInfoRef) {
10181
+ chatDataInfoRef.current[effectiveMode].conversations[savedConvId].messages.push(userMessage);
10182
+ chatDataRef.current[effectiveMode] = [
10183
+ ...(chatDataRef.current[effectiveMode] || []),
10184
+ userMessage,
10185
+ ];
10186
+ }
10187
+ // Build the response in the shape processResponse expects:
10188
+ // response.data.data.data = array of items
10189
+ const textItem = {
10190
+ type: "text",
10191
+ response: "",
10192
+ response_heading: "",
10193
+ thinkingResponse,
10194
+ };
10195
+ const responseData = [textItem, ...agentDataItems];
10196
+ const fakeResponse = {
10197
+ data: {
10198
+ data: {
10199
+ data: responseData,
10200
+ session_id: "",
10201
+ },
10202
+ },
10203
+ };
10204
+ // Call processResponse with steps/tabs context
10205
+ if (processResponse) {
10206
+ await processResponse(fakeResponse, {}, effectiveMode, null, {
10207
+ isTabEnabled: true,
10208
+ steps,
10209
+ currentTabValue: "agent_response",
10210
+ questions: [],
10211
+ questionsStepsMap: {},
10212
+ }, savedConvId);
10213
+ }
10214
+ setChatDataState({ ...chatDataRef.current });
10215
+ }
10216
+ catch (err) {
10217
+ setError(err.message);
10218
+ console.error("fetchConversationChats error:", err);
10219
+ }
10220
+ finally {
10221
+ setLoading(false);
10222
+ }
10223
+ }, [currentMode, processResponse]);
10224
+ const createNewConversation = useCallback(async (name) => {
10225
+ try {
10226
+ setLoading(true);
10227
+ const payload = {
10228
+ module_name: currentMode.toUpperCase(),
10229
+ flow_type: currentMode,
10230
+ name: name,
10231
+ application_code: 1,
10232
+ user_id: 251, // This should come from your auth context
10233
+ };
10234
+ const response = await createConversation(payload);
10235
+ if (response.status) {
10236
+ await fetchConversations$1();
10237
+ }
10238
+ }
10239
+ catch (err) {
10240
+ setError(err.message);
10241
+ }
10242
+ finally {
10243
+ setLoading(false);
10244
+ }
10245
+ }, [currentMode]);
10246
+ const renameConversation = useCallback(async (conversationId, newName, mode = null) => {
10247
+ const effectiveMode = mode || currentMode;
10248
+ try {
10249
+ setLoading(true);
10250
+ const payload = {
10251
+ conversation_id: conversationId,
10252
+ name: newName
10253
+ };
10254
+ const response = await updateConversation(conversationId, payload);
10255
+ // const response = {
10256
+ // status: true,
10257
+ // message: "Conversation updated successfully"
10258
+ // };
10259
+ if (response?.data?.status) {
10260
+ // chatDataRef.current[currentMode].conversations[conversationId].name = newName;
10261
+ if (chatDataInfoRef) {
10262
+ chatDataInfoRef.current[effectiveMode].conversations[conversationId].name = newName;
10263
+ }
10264
+ setChatDataState({ ...chatDataRef.current });
10265
+ return true;
10266
+ }
10267
+ setLoading(false);
10268
+ }
10269
+ catch (err) {
10270
+ setError(err.message);
10271
+ console.error("renameConversation error:", err);
10272
+ setLoading(false);
10273
+ }
10274
+ finally {
10275
+ setLoading(false);
10276
+ }
10277
+ }, [currentMode]);
10278
+ const deleteConversation$1 = useCallback(async (conversationId, mode = null) => {
10279
+ const effectiveMode = mode || currentMode;
10280
+ try {
10281
+ setLoading(true);
10282
+ const response = await deleteConversation(conversationId);
10283
+ // const response = {
10284
+ // status: true,
10285
+ // message: "Conversation deleted successfully"
10286
+ // };
10287
+ if (response?.data?.status) {
10288
+ // delete chatDataRef.current[currentMode].conversations[conversationId];
10289
+ if (chatDataInfoRef) {
10290
+ delete chatDataInfoRef.current[effectiveMode].conversations[conversationId];
10291
+ }
10292
+ setChatDataState({ ...chatDataRef.current });
10293
+ // If deleted conversation was active, select another one
10294
+ if (activeConversationId === conversationId) {
10295
+ const remainingConversations = Object.keys(chatDataRef.current[effectiveMode].conversations);
10296
+ setActiveConversationId(remainingConversations[0] || null);
10297
+ }
10298
+ return true;
10299
+ }
10300
+ }
10301
+ catch (err) {
10302
+ setError(err.message);
10303
+ }
10304
+ finally {
10305
+ setLoading(false);
10306
+ }
10307
+ }, [currentMode, activeConversationId]);
10308
+ const saveCurrentChat = useCallback(async () => {
10309
+ try {
10310
+ setLoading(true);
10311
+ let userId = await getCurrentUserId();
10312
+ let isNewConversation = false;
10313
+ let newConversationName = "New Conversation";
10314
+ const dataRef = chatDataInfoRef || chatDataRef;
10315
+ // If no active conversation is selected, create a new one
10316
+ if (!activeConversationId) {
10317
+ isNewConversation = true;
10318
+ const conversationCount = Object.keys(dataRef.current[currentMode].conversations).length;
10319
+ const newConversationId = Date.now(); // Using timestamp as unique ID
10320
+ newConversationName = `Conversation ${conversationCount + 1}`;
10321
+ // Create new conversation object
10322
+ dataRef.current[currentMode].conversations[newConversationId] = {
10323
+ id: newConversationId,
10324
+ name: newConversationName,
10325
+ timestamp: new Date().toISOString(),
10326
+ messages: dataRef.current[currentMode].conversations[activeConversationId]?.messages || []
10327
+ };
10328
+ // Update active conversation
10329
+ setActiveConversationId(newConversationId);
10330
+ setChatDataState({ ...chatDataRef.current });
10331
+ }
10332
+ const currentChat = dataRef.current[currentMode].conversations[activeConversationId];
10333
+ let currentSelectedModuleData = JSON.parse(localStorage.getItem("currentSelectedModuleData"));
10334
+ let currentSelectedModuleForInsights = localStorage.getItem("smartBotScreenName");
10335
+ // if (currentMode === "insights") {
10336
+ // currentSelectedModuleData = JSON.parse(
10337
+ // localStorage.getItem("smartBotScreenName")
10338
+ // );
10339
+ // }
10340
+ const payload = {
10341
+ conversation_id: currentChat?.idGenerated ? currentChat.id : null,
10342
+ module_name: currentMode === "insights" ? currentSelectedModuleForInsights : currentSelectedModuleData ? currentSelectedModuleData[activeConversationId] : "",
10343
+ flow_type: currentMode,
10344
+ name: isNewConversation ? newConversationName : currentChat.name,
10345
+ is_module_changed: isModuleChanged,
10346
+ chats: currentChat.messages.map(msg => ({
10347
+ chat_id: null, // null for new chat messages
10348
+ chat_object: {
10349
+ bodyText: msg.bodyText,
10350
+ bodyType: msg.bodyType === "stream" ? "text" : (msg.bodyType || 'text'),
10351
+ userName: msg.userName,
10352
+ userType: msg.userType,
10353
+ timeStamp: msg.timeStamp,
10354
+ headerTitle: msg.headerTitle,
10355
+ thinkingResponse: msg.thinkingResponse ? {
10356
+ thinkingStream: msg.thinkingResponse.thinkingStream,
10357
+ thinkingTime: msg.thinkingResponse.thinkingTime,
10358
+ thinkingHeading: msg.thinkingResponse.thinkingHeading,
10359
+ } : undefined,
10360
+ }
10361
+ }))
10362
+ };
10363
+ setIsModuleChanged(false);
10364
+ const response = await saveChat(payload);
10365
+ let newConversationId = null;
10366
+ if (response && response?.data?.status) {
10367
+ // Extract the new conversation data from the response
10368
+ const newConversationData = response?.data?.data?.data[0];
10369
+ if (newConversationData) {
10370
+ // Get the new conversation ID
10371
+ newConversationId = newConversationData.conversation_id;
10372
+ // Preserve the existing rich in-memory messages (they contain
10373
+ // thinkingResponse, combined bodyText arrays, JSX, etc. that
10374
+ // the server response does not return). Only update metadata.
10375
+ const existingMessages = currentChat.messages;
10376
+ // Map server-assigned chat_ids back onto existing messages
10377
+ if (newConversationData.chats) {
10378
+ newConversationData.chats.forEach((chat, index) => {
10379
+ if (existingMessages[index]) {
10380
+ existingMessages[index].id = chat.chat_id;
10381
+ }
10382
+ });
10383
+ }
10384
+ // Update conversation with server metadata but keep existing messages
10385
+ dataRef.current[currentMode].conversations[newConversationId] = {
10386
+ id: newConversationId,
10387
+ name: newConversationData.name,
10388
+ idGenerated: true,
10389
+ timestamp: newConversationData.created_at,
10390
+ messages: existingMessages,
10391
+ };
10392
+ // Keep chatDataRef in sync as well. Many parts of the UI re-render
10393
+ // based on setChatDataState({...chatDataRef.current}). If we only
10394
+ // update chatDataInfoRef, the UI can temporarily see an empty chat
10395
+ // and clear the conversation.
10396
+ if (chatDataInfoRef) {
10397
+ chatDataInfoRef.current[currentMode].conversations[newConversationId] = {
10398
+ id: newConversationId,
10399
+ name: newConversationData.name,
10400
+ idGenerated: true,
10401
+ timestamp: newConversationData.created_at,
10402
+ messages: existingMessages,
10403
+ };
10404
+ }
10405
+ // Update active conversation ID to the server-provided one
10406
+ setActiveConversationId(newConversationId);
10407
+ // Update the chat data state
10408
+ setChatDataState({ ...chatDataInfoRef.current });
10409
+ // Refresh the conversation list to show the new conversation
10410
+ await fetchConversations$1(newConversationId, "agent");
10411
+ }
10412
+ }
10413
+ }
10414
+ catch (err) {
10415
+ setError(err.message);
10416
+ console.error("saveCurrentChat error:", err);
10417
+ return false;
10418
+ }
10419
+ finally {
10420
+ setLoading(false);
10421
+ }
10422
+ }, [currentMode, activeConversationId, isModuleChanged]);
10423
+ return {
10424
+ loading,
10425
+ error,
10426
+ fetchConversations: fetchConversations$1,
10427
+ fetchConversationChats,
10428
+ createNewConversation,
10429
+ renameConversation,
10430
+ deleteConversation: deleteConversation$1,
10431
+ saveCurrentChat
10432
+ };
10433
+ };
9889
10434
 
9890
10435
  const SmartBot = (props) => {
9891
10436
  const { userName, partialClose, setPartialClose, forceOpen, customBaseUrl = "", displayQuestions, questions = [] } = props;
@@ -9897,6 +10442,9 @@ const SmartBot = (props) => {
9897
10442
  useState(false);
9898
10443
  const [conversation, setConversation] = useState({});
9899
10444
  const { chatbotContext, currentAgentChatId } = useSelector((state) => state.smartBotReducer);
10445
+ // Per-mode conversation ID tracking — prevents cross-mode contamination when
10446
+ // switching tabs while streams are pending.
10447
+ useRef({});
9900
10448
  const activeTab = useRef({
9901
10449
  activeTab: "dashboard",
9902
10450
  });
@@ -9913,12 +10461,14 @@ const SmartBot = (props) => {
9913
10461
  const [isLandingScreen, setIsLandingScreen] = useState(true);
9914
10462
  const [showSuggestionBanner, setShowSuggestionBanner] = useState(true);
9915
10463
  const [filterOptions, setFilterOptions] = useState([]);
9916
- const { setUserFlow, setUserScreenAndFlow, fetchUserResultsFromQuery, getCurrentDateTimeString, setLink, } = useChatFlow(chatDataRef, setLoader, setFlowType, setScreenName, setUserInput, setQuestionIndex, setCurrentAppLink, flowType, screenName, questionIndex, userInput, dateFormat, currentMode, activeConversationId, setIsModuleChanged, chatBodyRef, filterReducerState, dispatch, navigate, setShowChatPlaceholder, baseUrl, setChatDataState, setCurrentSessionId, customChatConfig, chatDataInfoRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, initValue, sessionId, fieldNumber, setFieldNumber, additionalArgs);
10464
+ useRef(0);
10465
+ const { setUserFlow, setUserScreenAndFlow, fetchUserResultsFromQuery, getCurrentDateTimeString, setLink, } = useChatFlow(chatDataRef, setLoader, setFlowType, setScreenName, setUserInput, setQuestionIndex, setCurrentAppLink, flowType, screenName, questionIndex, userInput, dateFormat, currentMode, activeConversationId, setIsModuleChanged, chatBodyRef, filterReducerState, dispatch, navigate, setShowChatPlaceholder, baseUrl, setChatDataState, setCurrentSessionId, customChatConfig, chatDataInfoRef, chatbotContext, setInitValue, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, uniqueChatId, initValue, sessionId, fieldNumber, setFieldNumber, additionalArgs, setActiveConversationId);
9917
10466
  const { parseSavedFlow, saveCurrentChanges, endCurrentSession, clearChatSession, initiateNewChat, hasUnsavedChanges, } = useChatSession(chatDataRef, setFlowType, setScreenName, setUserInput, setTemplateData, chatDataScreenLinkRef, setShowModal, setMinimizedMode, setSelectedModule, setChatDataState, currentMode, setUserFlow, getCurrentDateTimeString, setCurrentAppLink, selectedModule, fetchUserResultsFromQuery, props.closeBot, activeConversationId, setActiveConversationId, setShowChatPlaceholder);
9918
10467
  const { refreshAndUpdateUserManual, configureBotActions, displaySnackMessages, } = useBotConfiguration(setRefreshLoader, setEnableRefreshAction, dispatch);
9919
- const { prepareDataAndSendToAgent } = useAgentFlow(dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, baseUrl, setCurrentSessionId, customChatConfig, chatDataInfoRef, {
10468
+ const { prepareDataAndSendToAgent, processResponse } = useAgentFlow(dateFormat, chatDataRef, currentMode, setShowChatPlaceholder, setLoader, baseUrl, setCurrentSessionId, customChatConfig, chatDataInfoRef, {
9920
10469
  setChatDataState,
9921
10470
  activeConversationId,
10471
+ setActiveConversationId,
9922
10472
  chatBodyRef,
9923
10473
  runStreaming: true,
9924
10474
  chatbotContext,
@@ -10040,7 +10590,7 @@ const SmartBot = (props) => {
10040
10590
  [isLike ? "like" : "dislike"]: key,
10041
10591
  });
10042
10592
  handleMessageLike(key, isLike, setLoadingState, displaySnackMessages, templateData, activeConversationId, answer, chatDataInfoRef.current, chatIndex, setChatDataState, baseUrl, sessionId);
10043
- }, 5000, { trailing: false }), [loadingState, templateData, displaySnackMessages, sessionId, baseUrl]);
10593
+ }, 5000, { trailing: false }), [loadingState, templateData, displaySnackMessages, activeConversationId, sessionId, baseUrl]);
10044
10594
  useEffect(() => {
10045
10595
  handleUploadAccess();
10046
10596
  }, []);
@@ -10162,17 +10712,17 @@ const SmartBot = (props) => {
10162
10712
  }, [notificationData, baseUrl, currentAgentId, currentSessionId]);
10163
10713
  useEffect(() => {
10164
10714
  // Continue with current mode specific logic
10165
- if (chatDataInfoRef?.current[currentMode]?.conversations?.[1]?.messages
10715
+ if (chatDataInfoRef?.current[currentMode]?.conversations?.[activeConversationId]?.messages
10166
10716
  ?.length > 0) {
10167
10717
  // setConversation(chatDataInfoRef?.current[currentMode]?.conversations?.[1]?.messages);
10168
- let chatDataInfoRefLength = chatDataInfoRef?.current[currentMode]?.conversations?.[1]?.messages
10718
+ let chatDataInfoRefLength = chatDataInfoRef?.current[currentMode]?.conversations?.[activeConversationId]?.messages
10169
10719
  ?.length;
10170
- let chatDataInfoRefLastMessage = chatDataInfoRef?.current[currentMode]?.conversations?.[1]?.messages[chatDataInfoRefLength - 1];
10720
+ let chatDataInfoRefLastMessage = chatDataInfoRef?.current[currentMode]?.conversations?.[activeConversationId]?.messages[chatDataInfoRefLength - 1];
10171
10721
  if (chatDataInfoRefLastMessage?.bodyType === "stream") {
10172
- let newChatData = chatDataState?.[currentMode]?.conversations?.[null]?.messages;
10722
+ let newChatData = chatDataState?.[currentMode]?.conversations?.[activeConversationId]?.messages;
10173
10723
  let newChatDataLength = newChatData?.length - 1;
10174
10724
  if (newChatDataLength) {
10175
- chatDataInfoRef.current[currentMode].conversations[1].messages[chatDataInfoRefLength - 1] = cloneDeep(newChatData?.[newChatDataLength]);
10725
+ chatDataInfoRef.current[currentMode].conversations[activeConversationId].messages[chatDataInfoRefLength - 1] = cloneDeep(newChatData?.[newChatDataLength]);
10176
10726
  }
10177
10727
  }
10178
10728
  // let chatDataForReference = JSON.stringify(
@@ -10195,7 +10745,7 @@ const SmartBot = (props) => {
10195
10745
  customChatConfig: customChatConfig,
10196
10746
  loader: loader,
10197
10747
  };
10198
- const allMessages = chatDataInfoRef?.current[currentMode]?.conversations?.[1]?.messages || [];
10748
+ const allMessages = chatDataInfoRef?.current[currentMode]?.conversations?.[activeConversationId]?.messages || [];
10199
10749
  const lastBotMessageIndex = allMessages.reduce((lastIdx, msg, idx) => msg.userType === "bot" ? idx : lastIdx, -1);
10200
10750
  allMessages.forEach((message, index) => {
10201
10751
  if (message.userType === "bot") {
@@ -10208,8 +10758,20 @@ const SmartBot = (props) => {
10208
10758
  // />
10209
10759
  // ;
10210
10760
  message.isFormDisabled = index !== lastBotMessageIndex;
10211
- message.jsx = (jsx(BotMessage, { botData: message, state: loadingState, handleLikeDislike: handleLikeDislike, props: properties }));
10761
+ let originalUtilityObject = message.utilityObject;
10762
+ let newMessage = cloneDeep(message);
10763
+ if (originalUtilityObject) {
10764
+ newMessage.utilityObject = originalUtilityObject;
10765
+ }
10766
+ message.jsx = (jsx(BotMessage, { botData: newMessage, state: loadingState, handleLikeDislike: handleLikeDislike, props: properties }));
10212
10767
  message.firstMessage = true;
10768
+ let actualProps = {
10769
+ botData: newMessage,
10770
+ state: loadingState,
10771
+ handleLikeDislike: handleLikeDislike,
10772
+ props: properties,
10773
+ };
10774
+ message.actualProps = actualProps;
10213
10775
  // message.enableLikes = true;
10214
10776
  }
10215
10777
  });
@@ -10217,7 +10779,15 @@ const SmartBot = (props) => {
10217
10779
  let newChat = cloneDeep(chatDataInfoRef?.current[currentMode]);
10218
10780
  setConversation(newChat);
10219
10781
  }
10220
- }, [chatDataState, currentMode]);
10782
+ else if (showModal) {
10783
+ // Current mode has no messages — clear conversation so the previous
10784
+ // mode's components (including any active StreamedContent) unmount.
10785
+ // Without this, switching from agent→navigation while agent is streaming
10786
+ // would keep the agent's StreamedContent mounted and its response would
10787
+ // render in the navigation tab.
10788
+ setConversation({});
10789
+ }
10790
+ }, [chatDataState, currentMode, activeConversationId]);
10221
10791
  const fetchLegacyAgentInfo = async () => {
10222
10792
  try {
10223
10793
  let legacyAgentScreenData = await fetchLegacyAgentScreen();
@@ -10246,7 +10816,7 @@ const SmartBot = (props) => {
10246
10816
  return;
10247
10817
  }
10248
10818
  if (currentMode !== "agent") {
10249
- fetchUserResultsFromQuery({}, false, userInput);
10819
+ fetchUserResultsFromQuery({}, false, userInput, activeConversationId);
10250
10820
  }
10251
10821
  else if (customChatConfig?.useMiddleware) {
10252
10822
  let middleWareFunction = await getDynamicFunction(customChatConfig.middleWareFunctionPath, customChatConfig.middleWareFunctionName);
@@ -10256,8 +10826,6 @@ const SmartBot = (props) => {
10256
10826
  sessionId: currentSessionId,
10257
10827
  baseUrl: baseUrl,
10258
10828
  uniqueChatId: uniqueChatId,
10259
- userExplicitInput: userExplicitInput,
10260
- textWithColumnNames: textWithColumnNames,
10261
10829
  };
10262
10830
  let middleWareResponse = await middleWareFunction(data, chatBotInfoRef);
10263
10831
  if (middleWareResponse) {
@@ -10312,7 +10880,8 @@ const SmartBot = (props) => {
10312
10880
  setInitValue: setInitValue,
10313
10881
  uniqueChatId: uniqueChatId,
10314
10882
  currentAgentChatId: currentAgentChatId,
10315
- additionalArgs: isEmpty$1(userInput) ? additionalArgs : {}
10883
+ additionalArgs: isEmpty$1(userInput) ? additionalArgs : {},
10884
+ activeConversationId: activeConversationId,
10316
10885
  });
10317
10886
  setUserInput("");
10318
10887
  }
@@ -10459,13 +11028,38 @@ const SmartBot = (props) => {
10459
11028
  setBaseUrl(customBaseUrl);
10460
11029
  }
10461
11030
  }, [forceOpen]);
10462
- return (jsxs("div", { className: `${classes.agentStyleOverride} ${partialClose ? classes.hideBotStyle : ""}`, children: [jsx(MemoryModal, { isModalOpen: isModalOpen, setIsModalOpen: setIsModalOpen, displaySnackMessages: displaySnackMessages }), jsx(UploadModal, { isUploadModalOpen: isUploadModalOpen, setIsUploadModalOpen: setIsUploadModalOpen, displaySnackMessages: displaySnackMessages }), jsx(ChatBotComponent, { isFullWidth: forceOpen, userName: userName, showHistoryPanel: false, customInputComponent: currentMode === "agent" ? (jsx(ChatbotInput, { newChatScreen: newChatScreen, inputValue: userInput, setInputValue: setUserInput, isStopIcon: isStop, onSendIconClick: onSendIconClick, onStopIconClick: onStopIconClick, currentMode: currentMode, filterOptions: filterOptions })) : null, isChatBotOpen: showModal || forceOpen,
11031
+ const [historyPanelData, setHistoryPanelData] = useState([]);
11032
+ const { fetchConversations, saveCurrentChat, renameConversation, deleteConversation, fetchConversationChats, } = useConversationManagement(chatDataRef, currentMode, activeConversationId, setActiveConversationId, setChatDataState, selectedModule, setSelectedModule, isModuleChanged, setIsModuleChanged, undefined, undefined, chatDataInfoRef, setHistoryPanelData, processResponse);
11033
+ const handleHistoryMenuAction = useCallback(async (action, conversationData, renamedConversation = "") => {
11034
+ const conversationId = conversationData?.conversation_id;
11035
+ if (action === "rename") {
11036
+ await renameConversation(conversationId, renamedConversation, "agent");
11037
+ }
11038
+ else if (action === "delete") {
11039
+ await deleteConversation(conversationId, "agent");
11040
+ }
11041
+ fetchConversations(null, "agent");
11042
+ }, [renameConversation, deleteConversation, fetchConversations]);
11043
+ return (jsxs("div", { className: `${classes.agentStyleOverride} ${partialClose ? classes.hideBotStyle : ""} `, children: [jsx(MemoryModal, { isModalOpen: isModalOpen, setIsModalOpen: setIsModalOpen, displaySnackMessages: displaySnackMessages }), jsx(UploadModal, { isUploadModalOpen: isUploadModalOpen, setIsUploadModalOpen: setIsUploadModalOpen, displaySnackMessages: displaySnackMessages }), jsx(ChatBotComponent, { isFullWidth: forceOpen, userName: userName, showHistoryPanel: false, customInputComponent: currentMode === "agent" ? (jsx(ChatbotInput, { newChatScreen: newChatScreen, inputValue: userInput, setInputValue: setUserInput, isStopIcon: isStop, onSendIconClick: onSendIconClick, onStopIconClick: onStopIconClick, currentMode: currentMode, filterOptions: filterOptions, onSaveClick: saveCurrentChat })) : null, isChatBotOpen: showModal || forceOpen, historyPanelData: historyPanelData, onHistorySearchChange: (params) => { console.log("History Search Change", params); }, onHistorySelectConversation: (params) => {
11044
+ console.log("History Select Conversation", params);
11045
+ setNewChatScreen(false);
11046
+ setShowChatPlaceholder(false);
11047
+ fetchConversationChats(params?.conversation_id, "agent");
11048
+ }, onHistoryPanelClick: (p1, p2) => {
11049
+ console.log("History", p1, p2);
11050
+ fetchConversations(null, "agent");
11051
+ }, onHistoryMenuAction: (action, conversationData, renamedConversation) => {
11052
+ console.log("History Menu Action", action, conversationData);
11053
+ handleHistoryMenuAction(action, conversationData, renamedConversation);
11054
+ },
10463
11055
  // landingScreen={true}
10464
11056
  handleNewChatClick: () => {
10465
11057
  localStorage.setItem("isStreaming", "false");
10466
11058
  dispatch(setChatbotContext({}));
10467
11059
  setConversation([]);
10468
- chatDataInfoRef.current[currentMode] = [];
11060
+ chatDataInfoRef.current[currentMode] = {
11061
+ conversations: {},
11062
+ };
10469
11063
  setChatDataState({});
10470
11064
  if (currentMode === "agent") {
10471
11065
  setShowChatPlaceholder(true);
@@ -10534,8 +11128,10 @@ const SmartBot = (props) => {
10534
11128
  // );
10535
11129
  // return;
10536
11130
  // } else {
11131
+ const agentConversations = chatDataInfoRef?.current[params?.name?.toLowerCase()]?.conversations;
11132
+ const firstConversationId = agentConversations ? Object.keys(agentConversations)[0] : undefined;
10537
11133
  if (params?.name?.toLowerCase() === "agent") {
10538
- if (!isEmpty$1(chatDataInfoRef?.current[params?.name?.toLowerCase()])) {
11134
+ if (!isEmpty$1(agentConversations?.[firstConversationId]?.messages)) {
10539
11135
  setShowChatPlaceholder(false);
10540
11136
  }
10541
11137
  else {
@@ -10543,6 +11139,9 @@ const SmartBot = (props) => {
10543
11139
  }
10544
11140
  }
10545
11141
  setCurrentMode(params?.name?.toLowerCase());
11142
+ if (firstConversationId) {
11143
+ setActiveConversationId(firstConversationId);
11144
+ }
10546
11145
  localStorage.setItem("currentModeData", params?.name?.toLowerCase());
10547
11146
  setNewChatScreen(false);
10548
11147
  activeTab.current.activeTab = "agent";
@@ -10566,7 +11165,9 @@ const SmartBot = (props) => {
10566
11165
  // return;
10567
11166
  // } else {
10568
11167
  let currentModeValue = params?.name?.toLowerCase();
10569
- if (!isEmpty$1(chatDataInfoRef?.current[currentModeValue])) {
11168
+ const modeConversations = chatDataInfoRef?.current[currentModeValue]?.conversations;
11169
+ const firstConversationId = modeConversations ? Object.keys(modeConversations)[0] : undefined;
11170
+ if (!isEmpty$1(modeConversations?.[firstConversationId]?.messages)) {
10570
11171
  setNewChatScreen(false);
10571
11172
  }
10572
11173
  else {
@@ -10587,13 +11188,16 @@ const SmartBot = (props) => {
10587
11188
  // setNewChatScreen(true);
10588
11189
  setIsStop(false);
10589
11190
  setCurrentMode(params?.name?.toLowerCase());
11191
+ if (firstConversationId) {
11192
+ setActiveConversationId(firstConversationId);
11193
+ }
10590
11194
  // setConversation([]);
10591
11195
  // chatDataInfoRef.current[currentMode] = [];
10592
11196
  // }
10593
11197
  },
10594
11198
  icon: jsx(SvgNavigationIcon, {}),
10595
11199
  },
10596
- ], utilityList: utilityList, isAssistantThinking: loader, isCustomScreen: showChatPlaceholder, customScreenJsx: jsx(ChatPlaceholder, { dateFormat: dateFormat, chatDataRef: chatDataRef, currentMode: currentMode, setShowChatPlaceholder: setShowChatPlaceholder, setLoader: setLoader, setCurrentAgentId: setCurrentAgentId, baseUrl: baseUrl, setBaseUrl: setBaseUrl, setCurrentSessionId: setCurrentSessionId, customChatConfig: customChatConfig, chatDataInfoRef: chatDataInfoRef, setChatDataState: setChatDataState, userInput: userInput, legacyAgentScreen: legacyAgentScreen, activeConversationId: activeConversationId, chatBodyRef: chatBodyRef, chatbotContext: chatbotContext, setInitValue: setInitValue, setSessionId: setSessionId, thinkingContent: thinkingContext?.thinkingContent, setThinkingContent: setThinkingContent, isThinking: isThinking, setIsThinking: setIsThinking, chatId: chatId, setChatId: setChatId, isStop: isStop, setIsStop: setIsStop, functionsRef: functionsRef, functionsState: functionsState, setFunctionsState: setFunctionsState, thinkingHeaderMessage: thinkingContext?.thinkingHeaderMessage, setThinkingHeaderMessage: setThinkingHeaderMessage, uniqueChatId: uniqueChatId, setUniqueChatId: setUniqueChatId, fieldNumber: fieldNumber, setFieldNumber: setFieldNumber, setAdditionalArgs: setAdditionalArgs, displayQuestions: displayQuestions, questions: questions }), inputText: userInput, threadList: ["Home"], hideMenuArrow: hideMenu, newChatScreen: newChatScreen, isModuleListLoading: modulesLoading, suggestionBanner: {
11200
+ ], utilityList: utilityList, isAssistantThinking: loader, isCustomScreen: showChatPlaceholder, customScreenJsx: jsx(ChatPlaceholder, { dateFormat: dateFormat, chatDataRef: chatDataRef, currentMode: currentMode, setShowChatPlaceholder: setShowChatPlaceholder, setLoader: setLoader, setCurrentAgentId: setCurrentAgentId, baseUrl: baseUrl, setBaseUrl: setBaseUrl, setCurrentSessionId: setCurrentSessionId, customChatConfig: customChatConfig, chatDataInfoRef: chatDataInfoRef, setChatDataState: setChatDataState, userInput: userInput, legacyAgentScreen: legacyAgentScreen, activeConversationId: activeConversationId, chatBodyRef: chatBodyRef, chatbotContext: chatbotContext, setInitValue: setInitValue, setSessionId: setSessionId, thinkingContent: thinkingContext?.thinkingContent, setThinkingContent: setThinkingContent, isThinking: isThinking, setIsThinking: setIsThinking, chatId: chatId, setChatId: setChatId, isStop: isStop, setIsStop: setIsStop, functionsRef: functionsRef, functionsState: functionsState, setFunctionsState: setFunctionsState, thinkingHeaderMessage: thinkingContext?.thinkingHeaderMessage, setThinkingHeaderMessage: setThinkingHeaderMessage, uniqueChatId: uniqueChatId, setUniqueChatId: setUniqueChatId, fieldNumber: fieldNumber, setFieldNumber: setFieldNumber, setAdditionalArgs: setAdditionalArgs, displayQuestions: displayQuestions, questions: questions, setActiveConversationId: setActiveConversationId }), inputText: userInput, threadList: ["Home"], hideMenuArrow: hideMenu, newChatScreen: newChatScreen, isModuleListLoading: modulesLoading, suggestionBanner: {
10597
11201
  freeTextHeading: "Try adding more details :",
10598
11202
  freeTextContent: "Alan works better when you provide more context and pointed questions",
10599
11203
  }, isStopIcon: isStop, onStopIconClick: onStopIconClick, footerText: "AI-generated responses may contain errors\u2014please verify important information", showSuggestionBanner: showSuggestionBanner, onCloseSuggestionBanner: () => {
@@ -10610,6 +11214,9 @@ const SmartBot = (props) => {
10610
11214
  }
10611
11215
  const likeDislikeKey = `${params?.response_heading || params?.screen_name}_${params?.timeStamp}`;
10612
11216
  handleLikeDislike(likeDislikeKey, false, params?.bodyText, params2);
11217
+ }, handleSaveChat: () => {
11218
+ // Handle save chat logic here
11219
+ saveCurrentChat();
10613
11220
  } })] }));
10614
11221
  };
10615
11222