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

99.49% Statements 198/199
88.07% Branches 96/109
96.07% Functions 49/51
99.44% Lines 180/181

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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514                                          3x   3x 27x   4x 4x 1x     3x 1x       2x 1x     1x                                                                   3x   3x 420x 420x 2x   418x       3x 218x   3x 202x               3x   3x             152x 152x 152x   152x 152x 152x 152x 152x 152x 152x 152x   152x 143x 14x     152x 152x 152x 152x 152x 152x 152x   152x 50x 50x 50x         152x 34x 33x 33x 33x 33x 31x 31x 31x 2x                   2x     2x 2x         33x       152x 9x 9x 9x 9x 9x 9x 9x     152x   31x 31x   29x 2x 2x     27x 27x 27x   27x 27x         27x 27x 27x             27x 4x                 27x 27x 27x   27x   27x 27x               27x   27x 27x                   27x 5x 5x 5x 5x 10x       5x                 27x   5x 5x 10x 5x 5x 5x   5x   5x         6x 6x 6x 6x 12x       1x                     3x           27x 27x                   2x     27x         152x 5x 1x 1x     5x 5x 5x 5x 5x 5x 2x   5x 4x 4x 4x 1x                   1x     1x 1x         5x       152x 2x 1x 1x 1x 1x 1x 2x   2x   2x 1x                         1x                 152x   10x 8x 8x     12x     8x       7x 14x     7x 6x             6x     1x 1x                           1x   1x     8x           152x 152x                                               152x 135x                             152x   152x     3x 50x 50x   50x            
import React, { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
 
import { createContext, useContextSelector } from "use-context-selector";
 
import { useChatbotRuntime } from "@/contexts/ChatbotRuntimeContext";
 
import { BOT, USER } from "@/constants/chat";
 
import { Block, ChatMessage } from "@/types/chat";
 
import type { StreamCallbacks } from "@/services/chatbotService";
 
export { BOT, USER };
 
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() || "";
  if (!base64Value) {
    return null;
  }
 
  if (base64Value.startsWith("data:")) {
    return base64Value;
  }
 
  // Reject URL-like values (http, https, blob, file, etc.). The composer only sends uploaded image data.
  if (hasUrlScheme(base64Value)) {
    return null;
  }
 
  return `data:${image.type || "image/jpeg"};base64,${base64Value}`;
};
 
export interface ChatState {
  messages: ChatMessage[];
  threadId: string | null;
  text: string;
  isStreaming: boolean;
  isInitializing: boolean;
  initError: string | null;
  processingActionIds: string[];
  selectedImage: SelectedImage | null;
  userName: string | undefined;
}
 
export interface ChatActions {
  setText: (text: string) => void;
  setSelectedImage: (img: SelectedImage | null) => void;
  /** Resolves false when the message was rejected and the composer must keep its content. */
  onSend: (overrideText?: string) => Promise<boolean>;
  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;
  initThread: () => Promise<void>;
}
 
interface ChatContextValue {
  state: ChatState;
  actions: ChatActions;
}
 
const ChatbotContext = createContext<ChatContextValue | null>(null);
 
const useChatbotSelector = <T,>(selector: (ctx: ChatContextValue) => T): T => {
  return useContextSelector(ChatbotContext, (ctx) => {
    if (!ctx) {
      throw new Error("Chatbot context hooks must be used within ChatbotContextProvider");
    }
    return selector(ctx);
  });
};
 
export const useChatStateSelector = <T,>(selector: (state: ChatState) => T): T =>
  useChatbotSelector((ctx) => selector(ctx.state));
 
export const useChatActionsSelector = <T,>(selector: (actions: ChatActions) => T): T =>
  useChatbotSelector((ctx) => selector(ctx.actions));
 
interface CachedChatState {
  userId: string;
  messages: ChatMessage[];
  threadId: string | null;
}
 
let cachedChatState: CachedChatState | null = null;
 
const ChatbotContextProviderForUser = ({
  children,
  userId,
}: {
  children: ReactNode;
  userId: string | null;
}) => {
  const { meta } = useChatbotRuntime();
  const { service, scope, screenContext, userName } = meta;
  const initialCache = cachedChatState?.userId === userId ? cachedChatState : null;
 
  const [messages, setMessages] = useState<ChatMessage[]>(initialCache?.messages ?? []);
  const [threadId, setThreadId] = useState<string | null>(initialCache?.threadId ?? null);
  const [text, setText] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [isInitializing, setIsInitializing] = useState(false);
  const [initError, setInitError] = useState<string | null>(null);
  const [processingActionIds, setProcessingActionIds] = useState<string[]>([]);
  const [selectedImage, setSelectedImage] = useState<SelectedImage | null>(null);
 
  useEffect(() => {
    if (!userId) return;
    cachedChatState = { userId, messages, threadId };
  }, [messages, threadId, userId]);
 
  const abortControllerRef = useRef<{ abort: () => void } | null>(null);
  const textRef = useRef(text);
  textRef.current = text;
  const messagesRef = useRef(messages);
  messagesRef.current = messages;
  const selectedImageRef = useRef(selectedImage);
  selectedImageRef.current = selectedImage;
 
  useEffect(
    () => () => {
      abortControllerRef.current?.abort();
      abortControllerRef.current = null;
    },
    [],
  );
 
  const initThread = useCallback(async () => {
    if (threadId) return;
    setIsInitializing(true);
    setInitError(null);
    try {
      const res = await service.createThread(scope, screenContext);
      setInitError(null);
      setThreadId(res.thread.id);
      if (res.message) {
        const welcomeMsg: ChatMessage = {
          _id: `welcome_${Date.now()}`,
          text: res.message.text || "Welcome!",
          createdAt: new Date(),
          user: BOT,
          // No local greeting block: the welcome screen already greets the
          // user by name in its heading, and a second one here both repeated
          // it and shadowed the agent's own sentence about what it supports.
          blocks: res.message.blocks || [],
        };
        setMessages([welcomeMsg]);
      }
    } catch (error: any) {
      console.error("Failed to init thread", error);
      setInitError(
        error?.message ||
          "Failed to initialize conversation. Please check your connection and try again.",
      );
    } finally {
      setIsInitializing(false);
    }
  }, [threadId, service, scope, screenContext]);
 
  const clearChat = useCallback(() => {
    setMessages([]);
    setThreadId(null);
    setText("");
    setSelectedImage(null);
    setIsStreaming(false);
    setProcessingActionIds([]);
    setInitError(null);
  }, []);
 
  const onSend = useCallback(
    async (overrideText?: string) => {
      const finalText = (overrideText ?? textRef.current).trim();
      if ((!finalText && !selectedImageRef.current) || isStreaming) return false;
 
      if (!threadId) {
        setInitError("The conversation is still starting. Please try again in a moment.");
        return false;
      }
 
      setText("");
      const currentImage = selectedImageRef.current;
      setSelectedImage(null);
 
      const userMsgs: ChatMessage[] = [];
      const timestamp = Date.now();
      // Identity of THIS composed message, minted once here rather than per
      // send attempt. The server keys retry detection on it: re-sending with
      // the same id replays the stored turn instead of running the model a
      // second time. A per-attempt id would defeat that entirely.
      const clientMessageId = `${threadId}:${timestamp}:${Math.random().toString(36).slice(2, 10)}`;
      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) => {
        const withoutWelcome = prev.filter((m) => !String(m._id).startsWith("welcome_"));
        return [...userMsgs, ...withoutWelcome];
      });
      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) => [botMsg, ...prev]);
 
      const resolvedImageData = resolveImageData(currentImage);
      const imagePayload = resolvedImageData
        ? [
            {
              data: resolvedImageData,
              name: currentImage?.fileName,
              type: currentImage?.type,
            },
          ]
        : undefined;
 
      const markStreamFailed = (message: string) => {
        setIsStreaming(false);
        abortControllerRef.current = null;
        setMessages((prev) =>
          prev.map((m) =>
            m._id === botMsgId
              ? {
                  ...m,
                  blocks: [
                    ...(m.blocks?.map((b) => ({ ...b, isStreaming: false })) || []),
                    { type: "error", text: message },
                  ],
                }
              : m,
          ),
        );
      };
 
      const streamCallbacks: StreamCallbacks = {
        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: Block) => ({
                      ...b,
                      isStreaming: false,
                    })),
                    pendingAction: data.pendingAction,
                  }
                : m,
            ),
          );
        },
        onError: (error) => {
          markStreamFailed(
            error?.message || (typeof error === "string" ? error : "Failed to get response"),
          );
        },
      };
 
      try {
        abortControllerRef.current = await service.streamMessage(
          threadId,
          finalText,
          streamCallbacks,
          imagePayload,
          clientMessageId,
        );
      } catch (error: any) {
        // Opening the stream itself failed (token fetch, transport). Without
        // this the composer stays locked behind isStreaming forever.
        markStreamFailed(error?.message || "Failed to get response");
      }
 
      return true;
    },
    [isStreaming, threadId, service],
  );
 
  const onReset = useCallback(async () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
 
    setIsInitializing(true);
    setInitError(null);
    try {
      const currentThreadId = threadId;
      clearChat();
      if (currentThreadId) {
        await service.resetThread(currentThreadId).catch(() => {});
      }
      const res = await service.createThread(scope, screenContext);
      setInitError(null);
      setThreadId(res.thread.id);
      if (res.message) {
        const welcomeMsg: ChatMessage = {
          _id: `welcome_${Date.now()}`,
          text: res.message.text || "Thread reset.",
          createdAt: new Date(),
          user: BOT,
          // No local greeting block: the welcome screen already greets the
          // user by name in its heading, and a second one here both repeated
          // it and shadowed the agent's own sentence about what it supports.
          blocks: res.message.blocks || [],
        };
        setMessages([welcomeMsg]);
      }
    } catch (error: any) {
      console.error("Failed to reset thread", error);
      setInitError(
        error?.message ||
          "Failed to reset conversation. Please check your connection and try again.",
      );
    } finally {
      setIsInitializing(false);
    }
  }, [threadId, clearChat, service, scope, screenContext]);
 
  const handleCancel = useCallback(() => {
    if (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") => {
      if (!threadId || processingActionIds.includes(actionId)) return;
      setProcessingActionIds((prev) => [...prev, actionId]);
      try {
        // Read off the ref, not `messages`: re-creating handleAction on every
        // message would remount the confirmation buttons mid-submit.
        const actionType = messagesRef.current.find((m) => m._id === msgId)?.pendingAction?.type;
 
        const res =
          type === "confirm"
            ? await service.confirmAction(threadId, actionId, actionType)
            : await service.cancelAction(threadId, actionId);
 
        setMessages((prev) =>
          prev.map((m) => (m._id === msgId ? { ...m, pendingAction: null } : m)),
        );
 
        if (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) => [resultMsg, ...prev]);
        }
      } catch (error) {
        console.error(`Failed to ${type} action`, error);
        const errMsg: ChatMessage = {
          _id: `err_${Date.now()}`,
          text: "",
          createdAt: new Date(),
          user: BOT,
          blocks: [
            {
              type: "status",
              status: "error",
              description:
                "Sorry, something went wrong while processing your request. Please try again.",
            },
          ],
        };
        setMessages((prev) => [
          errMsg,
          ...prev.map((m) => (m._id === msgId ? { ...m, pendingAction: null } : m)),
        ]);
      } finally {
        setProcessingActionIds((prev) => prev.filter((id) => id !== actionId));
      }
    },
    [threadId, processingActionIds, service],
  );
 
  const state = useMemo<ChatState>(
    () => ({
      messages,
      threadId,
      text,
      isStreaming,
      isInitializing,
      initError,
      processingActionIds,
      selectedImage,
      userName,
    }),
    [
      messages,
      threadId,
      text,
      isStreaming,
      isInitializing,
      initError,
      processingActionIds,
      selectedImage,
      userName,
    ],
  );
 
  const actions = useMemo<ChatActions>(
    () => ({
      setText,
      setSelectedImage,
      onSend,
      onReset,
      handleCancel,
      handleAction,
      setMessages,
      setThreadId,
      clearChat,
      initThread,
    }),
    [onSend, onReset, handleCancel, handleAction, clearChat, initThread],
  );
 
  const value = useMemo<ChatContextValue>(() => ({ state, actions }), [state, actions]);
 
  return <ChatbotContext.Provider value={value}>{children}</ChatbotContext.Provider>;
};
 
export const ChatbotContextProvider = ({ children }: { children: ReactNode }) => {
  const { meta } = useChatbotRuntime();
  const userId = meta.userId ?? null;
 
  return (
    <ChatbotContextProviderForUser key={userId ?? "anonymous"} userId={userId}>
      {children}
    </ChatbotContextProviderForUser>
  );
};