All files / src/providers chatbot.tsx

92.8% Statements 271/292
80.7% Branches 46/57
100% Functions 6/6
92.8% Lines 271/292

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 4781x                     1x               1x               1x           1x             1x               1x 1x     1x     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x                                                     1x 1x 1x             1x 1x 1x   1x 25x 25x         25x 25x             1x     25x 16x 16x 25x     25x 25x 25x 25x 25x 25x   25x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x     25x 25x   25x     25x           25x     25x 16x       16x 13x   13x 13x 13x 16x   2x 2x 2x   25x     25x 25x         25x 25x 25x 25x 25x 25x 25x 25x     25x   25x   25x   25x 11x 11x     25x 8x 8x 8x   6x     6x 25x 25x 25x 25x 25x 25x 25x     25x   19x 17x 17x     2x 19x 19x   19x     1x           1x 1x 1x 1x 1x 1x 1x         25x 25x 25x 25x 25x 25x 25x 25x       25x 19x 10x 10x           19x   8x         8x         8x       8x 8x 8x   8x 8x 8x 8x 8x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x     25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 1x 1x 1x 1x 1x 1x 1x 1x     25x 25x 25x   25x             1x 15x 15x 15x 15x 15x   15x 11x 11x 11x 11x 11x 11x 11x 11x 11x 15x   15x 6x     6x 6x   6x 5x 5x 5x 5x 6x 1x 1x 1x 6x     6x 2x   2x 1x 1x 1x 1x 1x 1x 2x   6x     6x 6x     6x   6x 6x 6x 6x 6x 6x 15x   15x 15x 15x 15x 15x 15x 15x 15x     15x 15x   15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   15x 15x 15x   15x   1x 5x   5x 2x 2x   2x 2x  
import {
  createContext,
  Dispatch,
  ReactNode,
  SetStateAction,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  CopilotKit,
  useCopilotMessagesContext,
  useCopilotChat,
} from '@copilotkit/react-core';
import { Message } from '@copilotkit/runtime-client-gql';
 
// Constants
import {
  COOKIE_KEYS,
  COPILOTKIT_AGENTS,
  MESSAGES,
  WARNING_MESSAGE,
} from '@/constants';
 
// Utils
import {
  parsePersistentMessage,
  getChatbotThreadId,
  createNewChatbotThreadId,
  loadChatState,
} from '@/utils/chat';
import {
  suppressConsoleError,
  suppressConsoleWarnings,
  cookieStorage,
} from '@shared/utils';
 
// Stores
import {
  useChatInitialized,
  useChatMessages,
  useSetChatInitialized,
  useSetChatMessages,
} from '@/stores';
 
// Hooks
import { useChatMode } from '@/hooks/chat/useChatMode';
import { useChatbotActions } from '@/hooks/chat/useChatbotActions';
 
// Types
import { UserRole } from '@/types/auth';
 
// Components
import LoadingIndicator from '@/components/common/LoadingIndicator';
import { useStatistic } from './statistic';
import { ChartMode } from '@/types';
import { createWeekSelectedRanges } from '@/utils/calendar';
import { format } from 'date-fns';
import { auth } from '@/services';
import { onIdTokenChanged } from 'firebase/auth';
import { useAuthContext } from './auth';
 
export enum ChatMode {
  POPUP = 'popup',
  SIDEBAR = 'sidebar',
}
 
export interface SwitchChatModeOptions {
  targetMode?: ChatMode;
  forceOpen?: boolean;
}
 
export interface ChatProviderType {
  messages: Message[]; // This should be an array of message objects in a real application
  userId?: string;
  isLoading?: boolean;
  isProcessing: boolean;
  setIsProcessing: Dispatch<SetStateAction<boolean>>;
  uploadImage?: File;
  saveUploadImage: (value: File | null | undefined) => void;
 
  // Chatbot UI control
  isOpen: boolean;
  chatBotMode: ChatMode;
  toggleVisibility: () => void;
  switchChatMode: (options?: SwitchChatModeOptions) => void;
  openPopup: () => void;
  handleSwitchMode: () => void;
  resetChat: () => void;
}
 
export const ChatContext = createContext<ChatProviderType | undefined>(
  undefined,
);
 
export interface ThreadIdContextType {
  threadId: string;
  resetThreadId: () => void;
}
 
export const ThreadIdContext = createContext<ThreadIdContextType | undefined>(
  undefined,
);
 
export const useThreadIdContext = () => {
  const context = useContext(ThreadIdContext);
  if (!context) {
    throw new Error(
      'useThreadIdContext must be used within a ThreadIdContext.Provider',
    );
  }
  return context;
};
 
export type ChatProviderProps = {
  children: ReactNode;
  ChatBot?: ReactNode;
};
 
export const ChatProvider = ({ children }: ChatProviderProps) => {
  // Load messages from localStorage synchronously on mount
  // This ensures we have messages before any effects run
  const [initialMessages] = useState(() => {
    const state = loadChatState();
    return state.chatMessages;
  });
 
  // Store state/actions
  const storeMessages = useChatMessages();
  const isChatInitialized = useChatInitialized();
  const [isProcessing, setIsProcessing] = useState(false);
  const [actionId, saveActionId] = useState<string>('');
  const [prevActionId, savePrevActionId] = useState<string>('');
  const hasRestoredRef = useRef(false);
 
  const [uploadImage, saveUploadImage] = useState<File | null | undefined>(
    null,
  );
 
  const {
    isOpen,
    chatBotMode,
    toggleVisibility,
    switchChatMode,
    openPopup,
    handleSwitchMode,
  } = useChatMode();
 
  const user = null as unknown;
  const userEmail =
    (user as unknown as { primaryEmailAddress?: { emailAddress?: string } })
      ?.primaryEmailAddress?.emailAddress || '';
 
  // Messages context from CopilotKit
  const { messages, setMessages } = useCopilotMessagesContext();
  const { appendMessage, isLoading, reset } = useCopilotChat();
 
  const { resetThreadId } = useThreadIdContext();
 
  // Reset chat function - clears all messages from CopilotKit and store, then starts a new thread
  const resetChat = useCallback(() => {
    reset();
    setMessages([]);
    // Clear the store messages to prevent restoration
    useSetChatMessages([]);
    resetThreadId();
  }, [reset, setMessages, resetThreadId]);
 
  // Restore messages immediately on mount - this runs before other effects
  useEffect(() => {
    if (hasRestoredRef.current) {
      return;
    }
 
    if (!messages.length) {
      const parsedMessages = parsePersistentMessage(initialMessages);
      // Restore immediately, no delay needed since this is the first effect
      setMessages(parsedMessages);
      useSetChatInitialized(true);
      hasRestoredRef.current = true;
    } else if (initialMessages.length === 0) {
      // No messages to restore, mark as initialized
      hasRestoredRef.current = true;
      useSetChatInitialized(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Empty deps - only run once on mount
 
  // Suppress expected "Abort error suppressed" warnings from libs
  suppressConsoleWarnings(WARNING_MESSAGE.SUPPRESSED_ABORT);
  suppressConsoleError(WARNING_MESSAGE.SUPPRESSED_STREAM);
 
  /**
   * Call to init chatbot action
   */
  useChatbotActions({
    isProcessing,
    setIsProcessing,
    actionId,
    saveActionId,
    prevActionId,
    savePrevActionId,
  });
 
  // Track if we've done the initial sync to avoid overwriting restored messages
  const hasSyncedRef = useRef(false);
  // Track if we're currently restoring to prevent infinite loops
  const isRestoringRef = useRef(false);
 
  useEffect(() => {
    // Don't sync if chat hasn't been initialized yet (to allow restoration to happen first)
    if (!isChatInitialized) {
      return;
    }
 
    // On first sync after initialization, skip if messages are empty (they might be restoring)
    if (!hasSyncedRef.current && messages.length === 0) {
      hasSyncedRef.current = true;
      return;
    }
 
    hasSyncedRef.current = true;
    // Persist the chat data - always save current messages to store
    // This ensures messages are persisted whenever they change
    useSetChatMessages(messages);
  }, [
    appendMessage,
    isLoading,
    messages,
    useSetChatMessages,
    isChatInitialized,
  ]);
 
  // Fallback restoration effect - in case the synchronous restoration didn't work
  useEffect(() => {
    // Skip if already restored
    if (hasRestoredRef.current) {
      return;
    }
 
    // Use storeMessages if available, otherwise check localStorage directly
    const messagesToRestore =
      storeMessages.length > 0 ? storeMessages : initialMessages;
    const hasStoredMessages = messagesToRestore.length > 0;
 
    if (hasStoredMessages && !isChatInitialized && messages.length === 0) {
      // Wait for CopilotKit to finish loading before restoring
      // This prevents race conditions without using arbitrary timeouts
      if (isLoading) {
        return; // Will retry when isLoading becomes false
      }
 
      // Restore messages immediately - use queueMicrotask to ensure this runs
      // after the current render cycle but without arbitrary delay
      queueMicrotask(() => {
        const parsedMessages = parsePersistentMessage(messagesToRestore);
        setMessages(parsedMessages);
        useSetChatInitialized(true);
        hasRestoredRef.current = true;
      });
    } else if (!hasStoredMessages && !isChatInitialized) {
      // No stored messages, mark as initialized
      hasRestoredRef.current = true;
      useSetChatInitialized(true);
    }
  }, [
    isChatInitialized,
    storeMessages,
    initialMessages,
    messages.length,
    setMessages,
    isLoading,
  ]);
 
  // Watch for messages being cleared after restoration and restore again
  // This handles cases where CopilotKit resets messages after we restore them
  useEffect(() => {
    if (!hasRestoredRef.current || !isChatInitialized) {
      return;
    }
 
    // After initialization, only use storeMessages (not initialMessages)
    // This ensures that when we clear the store, we don't restore from stale initialMessages
    // Only restore if there are actually messages to restore
    // This prevents restoring after an intentional reset
    if (!messages.length) {
      // Prevent infinite loops by checking if we're already restoring
      if (isRestoringRef.current) {
        return;
      }
 
      // Wait for CopilotKit to finish loading to avoid race conditions
      if (isLoading) {
        return; // Will retry when isLoading becomes false
      }
 
      // Mark as restoring to prevent loops
      isRestoringRef.current = true;
 
      // Use queueMicrotask to restore after current execution cycle
      // This ensures we restore after CopilotKit's state updates complete
      queueMicrotask(() => {
        const parsedMessages = parsePersistentMessage(storeMessages);
        setMessages(parsedMessages);
        // Reset restoring flag after a microtask to allow future restorations
        queueMicrotask(() => {
          isRestoringRef.current = false;
        });
      });
    }
  }, [
    messages.length,
    storeMessages,
    isChatInitialized,
    setMessages,
    isLoading,
  ]);
 
  return (
    <ChatContext.Provider
      value={{
        messages,
        saveUploadImage,
        uploadImage: uploadImage ?? undefined,
        userId: userEmail,
        isProcessing,
        setIsProcessing,
 
        // Chatbot UI control
        isOpen,
        chatBotMode,
        toggleVisibility,
        switchChatMode,
        openPopup,
        handleSwitchMode,
        resetChat,
      }}
    >
      <>
        {isProcessing && (
          <div className="fixed inset-0 bg-background/2 backdrop-blur-sm z-50 flex-center transition-opacity duration-300">
            <LoadingIndicator
              size="lg"
              color="primary"
              center
              className="min-h-48"
            />
          </div>
        )}
 
        {children}
      </>
    </ChatContext.Provider>
  );
};
 
/**
 * We will provide more provider for Employee later
 * @param param0
 * @returns
 */
export const ChatBotWrapper = ({ children }: ChatProviderProps) => {
  const { user: userProfile } = useAuthContext();
  const [token, setToken] = useState<string | null>(null);
  const [userRole, setUserRole] = useState<string | null>(null);
  const isUser = token && userRole && userRole !== UserRole.ADMIN;
  const { filter, user } = useStatistic();
 
  useEffect(() => {
    const fetchToken = async () => {
      const currentUserRole = cookieStorage.getItem(COOKIE_KEYS.USER_ROLE);
      const token = await user?.getIdToken(true);
      setToken(token || '');
      setUserRole(currentUserRole);
    };
    if (user) {
      fetchToken();
    }
  }, [user]);
 
  useEffect(() => {
    let isMounted = true;
 
    // Listen for token changes or user state changes
    const unsubscribe = onIdTokenChanged(auth, async (currentUser) => {
      if (!isMounted) return;
 
      if (currentUser) {
        const token = await currentUser.getIdToken();
        const currentUserRole = cookieStorage.getItem(COOKIE_KEYS.USER_ROLE);
        setToken(token);
        setUserRole(currentUserRole);
      } else {
        setToken(null);
        setUserRole(null);
      }
    });
 
    // Force refresh token when user returns to tab
    const handleFocus = async () => {
      const currentUser = auth.currentUser;
 
      if (currentUser) {
        const freshToken = await currentUser.getIdToken(true);
        setToken(freshToken);
      } else {
        setToken(null);
        setUserRole(null);
      }
    };
 
    window.addEventListener('focus', handleFocus);
 
    // Refresh token about 10 mins before it expires
    const refreshMins =
      (Number(import.meta.env.PUBLIC_FIREBASE_TOKEN_EXPIRE_MINUTES) || 60) - 10;
 
    // Auto refresh token
    const interval = setInterval(handleFocus, refreshMins * 60 * 1000);
 
    return () => {
      isMounted = false;
      unsubscribe();
      window.removeEventListener('focus', handleFocus);
      clearInterval(interval);
    };
  }, []);
 
  const currentTimeRange =
    filter?.mode === ChartMode.Week
      ? createWeekSelectedRanges(filter?.timeRange)
          .map(
            (item) =>
              `${format(item.from, 'yyyyMMdd')},${format(item.to, 'yyyyMMdd')}`,
          )
          .join(',')
      : filter?.timeRange;
 
  const [threadId, setThreadId] = useState(() => getChatbotThreadId());
  const resetThreadId = useCallback(() => {
    setThreadId(createNewChatbotThreadId());
  }, []);
 
  return (
    <ThreadIdContext.Provider value={{ threadId, resetThreadId }}>
      <CopilotKit
        threadId={threadId}
        showDevConsole={false}
        runtimeUrl={`${COPILOTKIT_AGENTS.ENDPOINT}${COPILOTKIT_AGENTS.ROUTE}`}
        agent={COPILOTKIT_AGENTS.KITCHEN_AGENT}
        headers={{
          Authorization: `token=${token}&project_code=&isUser=${isUser}&currentTimeRange=${currentTimeRange}&currentMode=${filter?.mode}`,
        }}
        properties={{
          token,
          isUser,
          currentTimeRange,
          currentMode: filter?.mode,
        }}
      >
        <ChatProvider>{children}</ChatProvider>
      </CopilotKit>
    </ThreadIdContext.Provider>
  );
};
 
export const useChat = () => {
  const context = useContext(ChatContext);
 
  if (!context) {
    throw new Error(MESSAGES.OPTION_DATA_CONTEXT_ERROR);
  }
 
  return context;
};