All files / apps/host/src/contexts ChatContext.tsx

90.19% Statements 138/153
64.28% Branches 54/84
88.88% Functions 32/36
92.08% Lines 128/139

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                                5x 5x                 5x   5x 4x   1x 1x       1x         1x       1x                                                     5x   5x 30x 30x 30x 30x 30x 30x 30x           30x   30x 30x   30x 9x 8x 8x 8x 8x 8x 2x             2x         8x       30x 1x 1x 1x 1x 1x 1x     30x   4x 4x   4x 4x 4x 4x   4x 4x 4x 4x             4x 1x                 4x 4x   4x 4x               4x   4x 4x       4x         1x 1x 2x 1x 1x 1x   1x   1x         1x 1x 1x 1x 2x       1x               1x 1x   1x 1x 1x 2x       1x                       4x         30x 1x   1x         1x 1x 1x 1x 1x 1x 1x 1x 1x             1x         1x       30x 1x 1x 1x 1x 1x 1x 2x   2x   2x 1x                         1x                 30x   1x 1x 1x   1x       1x   1x 1x             1x         1x           30x       30x       30x 29x                                                                                     30x     5x 29x 29x 1x   28x    
import React, {
  createContext,
  ReactNode,
  useCallback,
  useContext,
  useMemo,
  useRef,
  useState,
} from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import { Keyboard } from 'react-native';
 
import { ChatMessage } from '@/types/chat';
 
import { chatbotService } from '@/services/chatbotService';
 
export const USER = { _id: 1 };
export const BOT = { _id: 2, name: 'Flash Bot' };
 
type SelectedImage = {
  uri: string;
  fileName?: string;
  type?: string;
  base64?: string;
};
 
const hasUrlScheme = (value: string) => /^[a-z][a-z0-9+.-]*:/i.test(value.trim());
 
const resolveImageData = (image: SelectedImage | null) => {
  if (!image) return null;
 
  const base64Value = image.base64?.trim() || '';
  Iif (!base64Value) {
    return null;
  }
 
  Iif (base64Value.startsWith('data:')) {
    return base64Value;
  }
 
  // Reject URL-like values (http, https, blob, file, etc.). ChatBox only sends uploaded image data.
  Iif (hasUrlScheme(base64Value)) {
    return null;
  }
 
  return `data:${image.type || 'image/jpeg'};base64,${base64Value}`;
};
 
interface ChatContextType {
  messages: ChatMessage[];
  threadId: string | null;
  text: string;
  isStreaming: boolean;
  isInitializing: boolean;
  processingActionIds: string[];
  selectedImage: { uri: string; fileName?: string; type?: string; base64?: string } | null;
  setText: (text: string) => void;
  setSelectedImage: (img: SelectedImage | null) => void;
  onSend: (overrideText?: string) => Promise<void>;
  onReset: () => Promise<void>;
  handleCancel: () => void;
  handleAction: (msgId: string, actionId: string, type: 'confirm' | 'cancel') => Promise<void>;
  setMessages: (messages: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => void;
  setThreadId: (id: string | null) => void;
  clearChat: () => void;
  closeChat: () => void;
  setCloseChat: (fn: () => void) => void;
  initThread: () => Promise<void>;
  fabOffset: number;
  setFabOffset: (offset: number) => void;
}
 
const ChatContext = createContext<ChatContextType | undefined>(undefined);
 
export const ChatProvider = ({ children }: { children: ReactNode }) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [threadId, setThreadId] = useState<string | null>(null);
  const [text, setText] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);
  const [isInitializing, setIsInitializing] = useState(false);
  const [processingActionIds, setProcessingActionIds] = useState<string[]>([]);
  const [selectedImage, setSelectedImage] = useState<{
    uri: string;
    fileName?: string;
    type?: string;
    base64?: string;
  } | null>(null);
  const [fabOffset, setFabOffset] = useState(0);
 
  const abortControllerRef = useRef<{ abort: () => void } | null>(null);
  const closeChatRef = useRef<(() => void) | null>(null);
 
  const initThread = useCallback(async () => {
    if (threadId) return;
    setIsInitializing(true);
    try {
      const res = await chatbotService.createThread();
      setThreadId(res.thread.id);
      if (res.message) {
        const welcomeMsg: ChatMessage = {
          _id: `welcome_${Date.now()}`,
          text: res.message.text || 'Welcome!',
          createdAt: new Date(),
          user: BOT,
          blocks: res.message.blocks,
        };
        setMessages([welcomeMsg]);
      }
    } catch (error) {
      console.error('Failed to init thread', error);
    } finally {
      setIsInitializing(false);
    }
  }, [threadId]);
 
  const clearChat = useCallback(() => {
    setMessages([]);
    setThreadId(null);
    setText('');
    setSelectedImage(null);
    setIsStreaming(false);
    setProcessingActionIds([]);
  }, []);
 
  const onSend = useCallback(
    async (overrideText?: string) => {
      const finalText = overrideText || text.trim();
      Iif ((!finalText && !selectedImage) || isStreaming || !threadId) return;
 
      Keyboard.dismiss();
      setText('');
      const currentImage = selectedImage;
      setSelectedImage(null);
 
      const userMsgs: ChatMessage[] = [];
      const timestamp = Date.now();
      Eif (finalText) {
        userMsgs.push({
          _id: `u_txt_${timestamp}`,
          text: finalText,
          createdAt: new Date(),
          user: USER,
        });
      }
      if (currentImage) {
        userMsgs.push({
          _id: `u_img_${timestamp}`,
          text: '',
          createdAt: new Date(),
          user: USER,
          image: currentImage.uri,
        });
      }
 
      setMessages(prev => GiftedChat.append(prev, userMsgs));
      setIsStreaming(true);
 
      const botMsgId = `b_${Date.now()}`;
      const botMsg: ChatMessage = {
        _id: botMsgId,
        text: '',
        createdAt: new Date(),
        user: BOT,
        blocks: [{ type: 'text', text: '', isStreaming: true }],
      };
 
      setMessages(prev => GiftedChat.append(prev, [botMsg]));
 
      const resolvedImageData = resolveImageData(currentImage);
      const imagePayload = resolvedImageData
        ? [{ data: resolvedImageData, name: currentImage?.fileName, type: currentImage?.type }]
        : undefined;
 
      const controller = await chatbotService.streamMessage(
        threadId,
        finalText,
        {
          onDelta: delta => {
            setMessages(prev =>
              prev.map(m => {
                if (m._id === botMsgId) {
                  const newText = m.text + delta;
                  const newBlocks = m.blocks?.map((b, i) =>
                    i === 0 && b.type === 'text' ? { ...b, text: newText } : b,
                  );
                  return { ...m, text: newText, blocks: newBlocks };
                }
                return m;
              }),
            );
          },
          onCompleted: data => {
            setIsStreaming(false);
            abortControllerRef.current = null;
            setMessages(prev =>
              prev.map(m =>
                m._id === botMsgId
                  ? {
                      ...m,
                      text: data.message.text || m.text,
                      blocks: data.message.blocks?.map((b: any) => ({ ...b, isStreaming: false })),
                      pendingAction: data.pendingAction,
                    }
                  : m,
              ),
            );
          },
          onError: error => {
            setIsStreaming(false);
            abortControllerRef.current = null;
            const errorMsg =
              error?.message || (typeof error === 'string' ? error : 'Failed to get response');
            setMessages(prev =>
              prev.map(m =>
                m._id === botMsgId
                  ? {
                      ...m,
                      blocks: [
                        ...(m.blocks?.map(b => ({ ...b, isStreaming: false })) || []),
                        { type: 'error', text: errorMsg },
                      ],
                    }
                  : m,
              ),
            );
          },
        },
        imagePayload,
      );
 
      abortControllerRef.current = controller;
    },
    [text, selectedImage, isStreaming, threadId],
  );
 
  const onReset = useCallback(async () => {
    Iif (!threadId) return;
 
    Iif (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
 
    setIsInitializing(true);
    try {
      const currentThreadId = threadId;
      clearChat();
      await chatbotService.resetThread(currentThreadId);
      const res = await chatbotService.createThread();
      setThreadId(res.thread.id);
      Eif (res.message) {
        const welcomeMsg: ChatMessage = {
          _id: `welcome_${Date.now()}`,
          text: res.message.text || 'Thread reset.',
          createdAt: new Date(),
          user: BOT,
          blocks: res.message.blocks,
        };
        setMessages([welcomeMsg]);
      }
    } catch (error) {
      console.error('Failed to reset thread', error);
    } finally {
      setIsInitializing(false);
    }
  }, [threadId, clearChat]);
 
  const handleCancel = useCallback(() => {
    Eif (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
      setIsStreaming(false);
      setMessages(prev =>
        prev.map(m => {
          const isBot = m.user._id === BOT._id;
          const isStreamingOrEmpty =
            m.text === '' || (m.blocks && m.blocks.length === 1 && m.blocks[0].isStreaming);
 
          if (isBot && isStreamingOrEmpty) {
            return {
              ...m,
              text: '',
              blocks: [
                {
                  type: 'status',
                  title: 'You stopped this response',
                  status: 'cancel_stream',
                },
              ],
            };
          }
 
          return {
            ...m,
            blocks: m.blocks?.map(b => ({ ...b, isStreaming: false })),
          };
        }),
      );
    }
  }, []);
 
  const handleAction = useCallback(
    async (msgId: string, actionId: string, type: 'confirm' | 'cancel') => {
      Iif (!threadId || processingActionIds.includes(actionId)) return;
      setProcessingActionIds(prev => [...prev, actionId]);
      try {
        const res =
          type === 'confirm'
            ? await chatbotService.confirmAction(threadId, actionId)
            : await chatbotService.cancelAction(threadId, actionId);
 
        setMessages(prev => prev.map(m => (m._id === msgId ? { ...m, pendingAction: null } : m)));
 
        Eif (res.message) {
          const resultMsg: ChatMessage = {
            _id: `res_${Date.now()}`,
            text: res.message.text || (type === 'confirm' ? 'Confirmed.' : 'Cancelled.'),
            createdAt: new Date(),
            user: BOT,
            blocks: res.message.blocks,
          };
          setMessages(prev => GiftedChat.append(prev, [resultMsg]));
        }
      } catch (error) {
        console.error(`Failed to ${type} action`, error);
      } finally {
        setProcessingActionIds(prev => prev.filter(id => id !== actionId));
      }
    },
    [threadId, processingActionIds],
  );
 
  const closeChat = useCallback(() => {
    closeChatRef.current?.();
  }, []);
 
  const setCloseChat = useCallback((fn: () => void) => {
    closeChatRef.current = fn;
  }, []);
 
  const value = useMemo(
    () => ({
      messages,
      threadId,
      text,
      isStreaming,
      isInitializing,
      processingActionIds,
      selectedImage,
      setText,
      setSelectedImage,
      onSend,
      onReset,
      handleCancel,
      handleAction,
      setMessages,
      setThreadId,
      clearChat,
      closeChat,
      setCloseChat,
      initThread,
      fabOffset,
      setFabOffset,
    }),
    [
      messages,
      threadId,
      text,
      isStreaming,
      isInitializing,
      processingActionIds,
      selectedImage,
      onSend,
      onReset,
      handleCancel,
      handleAction,
      clearChat,
      closeChat,
      setCloseChat,
      initThread,
      fabOffset,
    ],
  );
 
  return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
};
 
export const useChat = () => {
  const context = useContext(ChatContext);
  if (context === undefined) {
    throw new Error('useChat must be used within a ChatProvider');
  }
  return context;
};