Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python
28.4 KB
Raw Blame
"use client";

import {
  EllipsisVertical,
  FileText,
  Library,
  MessageSquare,
  Plus,
  Settings2,
  Trash2,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { useBulkDeleteSessionsMutation } from "@/app/api/mutations/useBulkDeleteSessionsMutation";
import { useDeleteSessionMutation } from "@/app/api/queries/useDeleteSessionMutation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { usePermissions } from "@/hooks/use-permissions";
import { useTypewriter } from "@/hooks/use-typewriter";
import { useChatSelection } from "@/hooks/useChatSelection";
import { FILES_REGEX } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { BulkDeleteButton } from "./bulk-delete-button";
import { DeleteSessionModal } from "./delete-session-modal";
import { KnowledgeFilterList } from "./knowledge-filter-list";

/** Renders a conversation title, typewriting it in when isFresh=true.
 * Calls onDone once the animation completes so the parent can clear
 * the fresh flag and prevent re-animation on revisit. */
function ConversationTitle({
  title,
  isFresh,
  onDone,
}: {
  title: string;
  isFresh: boolean;
  onDone?: () => void;
}) {
  const displayed = useTypewriter(title, isFresh, onDone);
  return <>{displayed}</>;
}

// Re-export the types for backward compatibility
export interface RawConversation {
  response_id: string;
  title: string;
  endpoint: string;
  messages: Array<{
    role: string;
    content: string;
    timestamp?: string;
    response_id?: string;
  }>;
  created_at?: string;
  last_activity?: string;
  previous_response_id?: string;
  total_messages: number;
  [key: string]: unknown;
}

export interface ChatConversation {
  response_id: string;
  title: string;
  endpoint: EndpointType;
  messages: Array<{
    role: string;
    content: string;
    timestamp?: string;
    response_id?: string;
  }>;
  created_at?: string;
  last_activity?: string;
  previous_response_id?: string;
  total_messages: number;
  [key: string]: unknown;
}

interface NavigationProps {
  conversations?: ChatConversation[];
  isConversationsLoading?: boolean;
  onNewConversation?: () => void;
  onSelectionChange?: (isSelecting: boolean) => void;
  onNavigate?: () => void;
}

export function Navigation({
  conversations = [],
  isConversationsLoading = false,
  onNewConversation,
  onSelectionChange,
  onNavigate,
}: NavigationProps = {}) {
  const isCloudBrand = useIsCloudBrand();
  const pathname = usePathname();
  const {
    endpoint,
    loadConversation,
    currentConversationId,
    setCurrentConversationId,
    startNewConversation,
    conversationDocs,
    conversationData,
    refreshConversations,
    placeholderConversation,
    setPlaceholderConversation,
    conversationLoaded,
    loading,
  } = useChat();
  const selection = useChatSelection({ onChange: onSelectionChange });

  useEffect(() => {
    onSelectionChange?.(selection.isSelecting);
  }, [selection.isSelecting, onSelectionChange]);

  const allIds = conversations.map((c) => c.response_id);

  const previousConversationCountRef = useRef(0);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [conversationToDelete, setConversationToDelete] =
    useState<ChatConversation | null>(null);
  const hasCompletedInitialLoad = useRef(false);
  const loadingPlaceholderKey = useRef(`loading-placeholder-${Date.now()}`);
  const [freshConversationId, setFreshConversationId] = useState<string | null>(
    null,
  );
  const [prevPlaceholder, setPrevPlaceholder] = useState(
    placeholderConversation,
  );

  const { selectedFilter, setSelectedFilter } = useKnowledgeFilter();

  // Delete session mutation
  const deleteSessionMutation = useDeleteSessionMutation({
    onSuccess: () => {
      toast.success("Conversation deleted successfully");

      // If we deleted the current conversation, select another one
      if (
        conversationToDelete &&
        currentConversationId === conversationToDelete.response_id
      ) {
        // Filter out the deleted conversation and find the next one
        const remainingConversations = conversations.filter(
          (conv) => conv.response_id !== conversationToDelete.response_id,
        );

        if (remainingConversations.length > 0) {
          // Load the first available conversation (most recent)
          loadConversation(remainingConversations[0]);
        } else {
          // No conversations left, start a new one
          setCurrentConversationId(null);
          if (onNewConversation) {
            onNewConversation();
          } else {
            refreshConversations();
            startNewConversation();
          }
        }
      }

      setDeleteModalOpen(false);
      setConversationToDelete(null);
    },
    onError: (error) => {
      toast.error(`Failed to delete conversation: ${error.message}`);
    },
  });

  const bulkDeleteMutation = useBulkDeleteSessionsMutation({
    onSuccess: (res) => {
      const deletedSet = new Set(res.deleted);

      if (res.failed.length == 0) {
        toast.success(`${res.deleted.length} conversations deleted`);
      } else {
        toast.success(
          `${res.deleted.length} deleted, ${res.failed.length} couldn't be removed`,
        );
      }

      // if we delete a conversation the user is currently on
      if (currentConversationId && deletedSet.has(currentConversationId)) {
        const remaining = conversations.filter(
          (c) => !deletedSet.has(c.response_id),
        );

        if (remaining.length > 0) {
          loadConversation(remaining[0]);
        } else {
          setCurrentConversationId(null);
          startNewConversation();
        }
      }

      selection.exit();
    },
    onError: (error) => {
      toast.error(`Failed to delete conversations: ${error.message}`);
    },
  });

  const handleNewConversation = () => {
    // Use the prop callback if provided, otherwise use the context method
    if (onNewConversation) {
      onNewConversation();
    } else {
      refreshConversations();
      startNewConversation();
    }

    if (typeof window !== "undefined") {
      window.dispatchEvent(new CustomEvent("newConversation"));
    }
  };

  const handleDeleteConversation = (
    conversation: ChatConversation,
    event?: React.MouseEvent,
  ) => {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }
    setConversationToDelete(conversation);
    setDeleteModalOpen(true);
  };

  const handleContextMenuAction = (
    action: string,
    conversation: ChatConversation,
  ) => {
    switch (action) {
      case "delete":
        handleDeleteConversation(conversation);
        break;
      // Add more actions here in the future (rename, duplicate, etc.)
      default:
        break;
    }
  };

  const confirmDeleteConversation = () => {
    if (conversationToDelete) {
      deleteSessionMutation.mutate({
        sessionId: conversationToDelete.response_id,
        endpoint: endpoint,
      });
    }
  };

  const { can, canAny } = usePermissions();
  const allRoutes = [
    {
      label: "Chat",
      icon: MessageSquare,
      href: "/chat",
      active: pathname === "/" || pathname.startsWith("/chat"),
      visible: can("chat:use"),
    },
    {
      label: "Knowledge",
      icon: Library,
      href: "/knowledge",
      active: pathname.startsWith("/knowledge"),
      visible: canAny([
        "knowledge:read:own",
        "knowledge:read:all",
        "knowledge:upload",
      ]),
    },
    {
      label: "Settings",
      icon: Settings2,
      href: "/settings",
      active: pathname.startsWith("/settings"),
      visible: true, // always — content inside is gated
    },
  ];
  const routes = allRoutes.filter((r) => r.visible);

  const isOnChatPage = pathname === "/" || pathname === "/chat";
  const isOnKnowledgePage = pathname.startsWith("/knowledge");

  // Track when initial load completes
  useEffect(() => {
    if (!isConversationsLoading && !hasCompletedInitialLoad.current) {
      hasCompletedInitialLoad.current = true;
      previousConversationCountRef.current = conversations.length;
    }
  }, [isConversationsLoading, conversations.length]);

  if (prevPlaceholder !== placeholderConversation) {
    setPrevPlaceholder(placeholderConversation);
    if (prevPlaceholder && !placeholderConversation && currentConversationId) {
      setFreshConversationId(currentConversationId);
    }
  }

  // Clear placeholder when conversation count increases (new conversation was created)
  useEffect(() => {
    const currentCount = conversations.length;
    if (
      placeholderConversation &&
      hasCompletedInitialLoad.current &&
      currentCount > previousConversationCountRef.current &&
      conversations.length > 0 &&
      !isConversationsLoading
    ) {
      setPlaceholderConversation(null);
      const newestConversation = conversations[0];
      if (newestConversation) {
        setCurrentConversationId(newestConversation.response_id);
      }
    }

    if (hasCompletedInitialLoad.current) {
      previousConversationCountRef.current = currentCount;
    }
  }, [
    conversations.length,
    placeholderConversation,
    setPlaceholderConversation,
    conversations,
    setCurrentConversationId,
    isConversationsLoading,
  ]);

  useEffect(() => {
    let activeConvo;

    if (currentConversationId && conversations.length > 0) {
      activeConvo = conversations.find(
        (conv) => conv.response_id === currentConversationId,
      );
    }

    if (isOnChatPage && !isConversationsLoading) {
      if (conversations.length === 0 && !placeholderConversation) {
        // Auto-load: no conversations — reset state without showing a placeholder
        startNewConversation({ showPlaceholder: false });
      } else if (activeConvo) {
        loadConversation(activeConvo);
        // Don't call refreshConversations here - it causes unnecessary refetches
      } else if (
        conversations.length > 0 &&
        currentConversationId === null &&
        !placeholderConversation
      ) {
        // Auto-load: has conversations but none selected — reset without placeholder
        startNewConversation({ showPlaceholder: false });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- startNewConversation and loadConversation
    // are stable useCallback refs; placeholderConversation and currentConversationId are read inside
    // the effect but intentionally omitted to avoid re-running on every state change.
  }, [isOnChatPage, conversations, conversationLoaded]);

  const newConversationFiles = conversationData?.messages
    .filter(
      (message) =>
        message.role === "user" &&
        (message.content.match(FILES_REGEX)?.[0] ?? null) !== null,
    )
    .map((message) => message.content.match(FILES_REGEX)?.[0] ?? null)
    .concat(conversationDocs.map((doc) => doc.filename));

  return (
    <div className="flex flex-col h-full bg-background">
      <div className="px-4 py-2 shrink-0">
        <div className="space-y-1">
          {routes.map((route) => {
            const isDisabled = loading && !route.active;
            const tabClassName = cn(
              "text-mmd group flex p-3 w-full justify-start font-medium transition-all",
              isDisabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
              isCloudBrand
                ? route.active
                  ? "border-l-[3px] border-l-primary bg-(--layered-select-bg) text-foreground rounded-r-lg"
                  : cn(
                      "border-l-[3px] border-l-transparent text-foreground rounded-lg",
                      !isDisabled &&
                        "hover:bg-accent hover:text-accent-foreground",
                    )
                : cn(
                    "rounded-lg",
                    route.active
                      ? "bg-accent text-accent-foreground shadow-xs"
                      : "text-foreground",
                    !isDisabled &&
                      "hover:bg-accent hover:text-accent-foreground",
                  ),
            );
            const tabContent = (
              <div className="flex items-center flex-1">
                <route.icon
                  className={cn(
                    "h-[18px] w-[18px] mr-2 shrink-0",
                    isCloudBrand
                      ? "text-foreground"
                      : route.active
                        ? "text-muted-foreground"
                        : "text-muted-foreground group-hover:text-muted-foreground",
                  )}
                />
                {route.label}
              </div>
            );
            return (
              <div key={route.href}>
                {isDisabled ? (
                  <div className={tabClassName}>{tabContent}</div>
                ) : (
                  <Link
                    href={route.href}
                    className={tabClassName}
                    onClick={onNavigate}
                  >
                    {tabContent}
                  </Link>
                )}
                {route.label === "Settings" && (
                  <div className="my-2 border-t border-border" />
                )}
              </div>
            );
          })}
        </div>
      </div>

      {isOnKnowledgePage && (
        <KnowledgeFilterList
          selectedFilter={selectedFilter}
          onFilterSelect={setSelectedFilter}
        />
      )}

      {/* Chat Page Specific Sections */}
      {isOnChatPage && (
        <div className="flex-1 min-h-0 flex flex-col px-4">
          {/* Conversations Section */}
          <div className="shrink-0">
            <div className="flex items-center justify-between mb-3 mx-3">
              <h3 className="text-xs font-medium text-muted-foreground">
                Conversations
              </h3>
              <div className="flex items-center gap-1">
                {!selection.isSelecting && (
                  <button
                    type="button"
                    className="p-1 hover:bg-accent rounded"
                    data-testid="new-conversation-button"
                    onClick={handleNewConversation}
                    title="Start new conversation"
                    disabled={loading}
                  >
                    <Plus
                      className={cn(
                        "h-4 w-4",
                        isCloudBrand
                          ? "text-foreground"
                          : "text-muted-foreground",
                      )}
                    />
                  </button>
                )}
                <button
                  type="button"
                  data-testid="chat-select-toggle"
                  className="text-xs text-muted-foreground hover:text-foreground px-2 py-1 rounded hover:bg-accent bg-accent/50"
                  onClick={() =>
                    selection.isSelecting ? selection.exit() : selection.enter()
                  }
                >
                  {selection.isSelecting ? "Cancel" : "Select"}
                </button>
              </div>
            </div>
          </div>

          <div className="flex-1 min-h-0 overflow-y-auto scrollbar-hide">
            <div className="space-y-1 flex flex-col">
              {/* Show skeleton loaders when loading and no conversations exist */}
              {isConversationsLoading && conversations.length === 0 ? (
                [0, 1].map((skeletonIndex) => (
                  <div
                    key={`conversation-skeleton-${skeletonIndex}`}
                    className={cn(
                      "w-full px-3 h-11 rounded-lg animate-pulse",
                      skeletonIndex === 0 ? "bg-accent/50" : "",
                    )}
                  >
                    <div className="h-3 bg-muted-foreground/20 rounded w-3/4 mt-3.5" />
                  </div>
                ))
              ) : (
                <>
                  {/* Show regular conversations */}
                  {conversations.length === 0 &&
                  !isConversationsLoading &&
                  !placeholderConversation ? (
                    <div className="text-mmd text-muted-foreground py-2 pl-3">
                      No conversations yet
                    </div>
                  ) : (
                    <>
                      {/* Optimistic rendering: Show placeholder conversation button while loading */}
                      {(() => {
                        // Show placeholder when:
                        // 1. placeholderConversation is set (e.g. immediately after clicking +), OR
                        // 2. Loading is true AND conversation doesn't exist yet (mid-stream), OR
                        // 3. currentConversationId exists but isn't in conversations yet
                        const conversationExists = currentConversationId
                          ? conversations.some(
                              (conv) =>
                                conv.response_id === currentConversationId,
                            )
                          : false;

                        const shouldShowPlaceholder =
                          placeholderConversation !== null ||
                          (!conversationExists &&
                            (loading ||
                              (currentConversationId !== null &&
                                currentConversationId !== undefined)));

                        // Use placeholderConversation if available
                        // Otherwise create a placeholder with currentConversationId if it exists
                        // Or use a temporary ID if we're loading but don't have an ID yet
                        const placeholderToShow = placeholderConversation
                          ? placeholderConversation
                          : currentConversationId
                            ? {
                                response_id: currentConversationId,
                                title: "",
                                endpoint: endpoint,
                                messages: [],
                                total_messages: 0,
                              }
                            : loading
                              ? {
                                  response_id: loadingPlaceholderKey.current,
                                  title: "",
                                  endpoint: endpoint,
                                  messages: [],
                                  total_messages: 0,
                                }
                              : null;

                        return (
                          shouldShowPlaceholder &&
                          placeholderToShow && (
                            <button
                              key={placeholderToShow.response_id}
                              type="button"
                              className="w-full px-3 h-11 rounded-lg bg-accent group relative text-left cursor-not-allowed"
                              disabled
                            >
                              <div className="flex items-center justify-between">
                                <div className="flex-1 min-w-0">
                                  <div className="text-sm font-medium text-foreground truncate">
                                    New chat...
                                  </div>
                                </div>
                              </div>
                            </button>
                          )
                        );
                      })()}
                      {selection.isSelecting && (
                        <div className="flex items-center justify-between p-2 text-sm">
                          <label className="flex items-center gap-2 cursor-pointer font-bold">
                            <input
                              type="checkbox"
                              aria-label="Select all conversations"
                              data-testid="chat-select-all"
                              checked={selection.isAllSelected(allIds)}
                              onChange={() => selection.toggleAll(allIds)}
                            />
                            Select all
                          </label>
                          <span className="text-muted-foreground/50 text-xs">
                            {conversations.length} chats
                          </span>
                        </div>
                      )}
                      {conversations.map((conversation) => (
                        <button
                          key={conversation.response_id}
                          data-testid={`conversation-button-${conversation.title}`}
                          type="button"
                          className={`w-full h-11 rounded-lg group relative text-left ${
                            selection.isSelecting ? "px-2" : "px-3"
                          } ${
                            loading || isConversationsLoading
                              ? "opacity-50 cursor-not-allowed"
                              : "hover:bg-accent cursor-pointer"
                          } ${
                            currentConversationId === conversation.response_id
                              ? "bg-accent"
                              : ""
                          }`}
                          onClick={() => {
                            if (selection.isSelecting) {
                              selection.toggle(conversation.response_id);
                              return;
                            }
                            if (loading || isConversationsLoading) return;
                            loadConversation(conversation);
                            onNavigate?.();
                            // Don't refresh - just loading an existing conversation
                          }}
                          disabled={loading || isConversationsLoading}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex min-w-0">
                              {selection.isSelecting && (
                                <input
                                  type="checkbox"
                                  aria-label={`Select ${conversation.title}`}
                                  data-testid={`chat-select-${conversation.response_id}`}
                                  checked={selection.selectedIds.has(
                                    conversation.response_id,
                                  )}
                                  onChange={() =>
                                    selection.toggle(conversation.response_id)
                                  }
                                  onClick={(e) => e.stopPropagation()}
                                  className="mr-2 shrink-0"
                                />
                              )}
                              <div className="text-sm font-medium text-foreground truncate">
                                <ConversationTitle
                                  title={conversation.title}
                                  isFresh={
                                    freshConversationId ===
                                    conversation.response_id
                                  }
                                  onDone={
                                    freshConversationId ===
                                    conversation.response_id
                                      ? () => setFreshConversationId(null)
                                      : undefined
                                  }
                                />
                              </div>
                            </div>
                            {!selection.isSelecting && (
                              <DropdownMenu>
                                <DropdownMenuTrigger
                                  disabled={
                                    loading ||
                                    isConversationsLoading ||
                                    deleteSessionMutation.isPending
                                  }
                                  asChild
                                >
                                  <div
                                    className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 data-[state=open]:text-foreground transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground ml-2 shrink-0 cursor-pointer"
                                    title="More options"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                    }}
                                  >
                                    <EllipsisVertical className="h-4 w-4" />
                                  </div>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent
                                  side="bottom"
                                  align="end"
                                  className="w-48"
                                  onClick={(e) => e.stopPropagation()}
                                >
                                  <DropdownMenuItem
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleContextMenuAction(
                                        "delete",
                                        conversation,
                                      );
                                    }}
                                    className="cursor-pointer text-destructive focus:text-destructive"
                                  >
                                    <Trash2 className="mr-2 h-4 w-4" />
                                    Delete conversation
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            )}
                          </div>
                        </button>
                      ))}
                    </>
                  )}
                </>
              )}
            </div>
            {(newConversationFiles?.length ?? 0) !== 0 && (
              <div className="shrink-0 mt-4">
                <div className="flex items-center justify-between mb-3 mx-3">
                  <h3 className="text-xs font-medium text-muted-foreground">
                    Files
                  </h3>
                </div>
                <div className="overflow-y-auto scrollbar-hide space-y-1">
                  {newConversationFiles?.map((file, index) => (
                    <div
                      key={`${file}-${index}`}
                      className="flex-1 min-w-0 px-3"
                    >
                      <div className="text-mmd font-medium text-foreground truncate">
                        {file}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
          {selection.isSelecting && (
            <div className="shrink-0 py-3 border-t mx-3">
              <div className="flex items-center justify-between pb-1 text-xs text-muted-foreground">
                <span>{selection.count} selected</span>
                <span>of {conversations.length}</span>
              </div>
              <div className="pt-1 pb-3 w-full">
                <BulkDeleteButton
                  count={selection.count}
                  isDeleting={bulkDeleteMutation.isPending}
                  onDelete={() =>
                    bulkDeleteMutation.mutate({
                      session_ids: [...selection.selectedIds],
                      endpoint,
                    })
                  }
                />
              </div>
            </div>
          )}
        </div>
      )}

      {/* Delete Session Modal */}
      <DeleteSessionModal
        isOpen={deleteModalOpen}
        onClose={() => {
          setDeleteModalOpen(false);
          setConversationToDelete(null);
        }}
        onConfirm={confirmDeleteConversation}
        sessionTitle={conversationToDelete?.title || ""}
        isDeleting={deleteSessionMutation.isPending}
      />
    </div>
  );
}