Replacing researcher chat components with new chat page and components

This commit is contained in:
Utkarsh-Patel-13 2025-07-25 19:12:09 -07:00
parent 96d9ee68a3
commit 1dd373a700
12 changed files with 10 additions and 2658 deletions

View file

@ -0,0 +1,62 @@
"use client";
import React from "react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { ExternalLink } from "lucide-react";
export const CitationDisplay: React.FC<{ index: number; node: any }> = ({
index,
node,
}) => {
const truncateText = (text: string, maxLength: number = 200) => {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + "...";
};
const handleUrlClick = (e: React.MouseEvent, url: string) => {
e.preventDefault();
e.stopPropagation();
window.open(url, "_blank", "noopener,noreferrer");
};
return (
<Popover>
<PopoverTrigger asChild>
<span className="text-[10px] font-bold bg-slate-500 hover:bg-slate-600 text-white rounded-full w-4 h-4 inline-flex items-center justify-center align-super cursor-pointer transition-colors">
{index + 1}
</span>
</PopoverTrigger>
<PopoverContent className="w-80 p-4 space-y-3 relative" align="start">
{/* External Link Button - Top Right */}
{node?.url && (
<button
onClick={(e) => handleUrlClick(e, node.url)}
className="absolute top-3 right-3 inline-flex items-center justify-center w-6 h-6 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors"
title="Open in new tab"
>
<ExternalLink size={14} />
</button>
)}
{/* Heading */}
<div className="text-sm font-semibold text-slate-900 dark:text-slate-100 pr-8">
{node?.metadata?.group_name || "Source"}
</div>
{/* Source */}
<div className="text-xs text-slate-600 dark:text-slate-400 font-medium">
{node?.metadata?.title || "Untitled"}
</div>
{/* Body */}
<div className="text-xs text-slate-700 dark:text-slate-300 leading-relaxed">
{truncateText(node?.text || "No content available")}
</div>
</PopoverContent>
</Popover>
);
};

View file

@ -0,0 +1,45 @@
"use client";
import { SuggestedQuestions } from "@llamaindex/chat-ui/widgets";
import { getAnnotationData, Message, useChatUI } from "@llamaindex/chat-ui";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
export const ChatFurtherQuestions: React.FC<{ message: Message }> = ({
message,
}) => {
const annotations: string[][] = getAnnotationData(
message,
"FURTHER_QUESTIONS",
);
const { append, requestData } = useChatUI();
if (annotations.length !== 1 || annotations[0].length === 0) {
return <></>;
}
return (
<Accordion
type="single"
collapsible
className="w-full px-2 border-2 rounded-lg shadow-lg"
>
<AccordionItem value="suggested-questions">
<AccordionTrigger className="text-sm font-semibold">
Suggested Questions
</AccordionTrigger>
<AccordionContent>
<SuggestedQuestions
questions={annotations[0]}
append={append}
requestData={requestData}
/>
</AccordionContent>
</AccordionItem>
</Accordion>
);
};

View file

@ -0,0 +1,617 @@
"use client";
import { ChatInput } from "@llamaindex/chat-ui";
import { FolderOpen, Check, Zap, Brain } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
DialogFooter,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Suspense, useState, useCallback } from "react";
import { useParams } from "next/navigation";
import { useDocuments, Document } from "@/hooks/use-documents";
import { DocumentsDataTable } from "@/components/chat/DocumentsDataTable";
import { useSearchSourceConnectors } from "@/hooks/useSearchSourceConnectors";
import {
getConnectorIcon,
ConnectorButton as ConnectorButtonComponent,
} from "@/components/chat/ConnectorComponents";
import { ResearchMode } from "@/components/chat";
import { useLLMConfigs, useLLMPreferences } from "@/hooks/use-llm-configs";
import React from "react";
const DocumentSelector = React.memo(
({
onSelectionChange,
selectedDocuments = [],
}: {
onSelectionChange?: (documents: Document[]) => void;
selectedDocuments?: Document[];
}) => {
const { search_space_id } = useParams();
const [isOpen, setIsOpen] = useState(false);
const { documents, loading, isLoaded, fetchDocuments } = useDocuments(
Number(search_space_id),
true,
);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open && !isLoaded) {
fetchDocuments();
}
},
[fetchDocuments, isLoaded],
);
const handleSelectionChange = useCallback(
(documents: Document[]) => {
onSelectionChange?.(documents);
},
[onSelectionChange],
);
const handleDone = useCallback(() => {
setIsOpen(false);
}, []);
const selectedCount = React.useMemo(
() => selectedDocuments.length,
[selectedDocuments.length],
);
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" className="relative">
<FolderOpen className="w-4 h-4" />
{selectedCount > 0 && (
<span className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
{selectedCount}
</span>
)}
</Button>
</DialogTrigger>
<DialogContent className="max-w-[95vw] md:max-w-5xl h-[90vh] md:h-[85vh] p-0 flex flex-col">
<div className="flex flex-col h-full">
<div className="px-4 md:px-6 py-4 border-b flex-shrink-0">
<DialogTitle className="text-lg md:text-xl">
Select Documents
</DialogTitle>
<DialogDescription className="mt-1 text-sm">
Choose documents to include in your research context
</DialogDescription>
</div>
<div className="flex-1 min-h-0 p-4 md:p-6">
{loading ? (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<div className="animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full mx-auto" />
<p className="text-sm text-muted-foreground">
Loading documents...
</p>
</div>
</div>
) : isLoaded ? (
<DocumentsDataTable
documents={documents}
onSelectionChange={handleSelectionChange}
onDone={handleDone}
initialSelectedDocuments={selectedDocuments}
/>
) : null}
</div>
</div>
</DialogContent>
</Dialog>
);
},
);
DocumentSelector.displayName = "DocumentSelector";
const ConnectorSelector = React.memo(
({
onSelectionChange,
selectedConnectors = [],
}: {
onSelectionChange?: (connectorTypes: string[]) => void;
selectedConnectors?: string[];
}) => {
const [isOpen, setIsOpen] = useState(false);
const { connectorSourceItems, isLoading, isLoaded, fetchConnectors } =
useSearchSourceConnectors(true);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open && !isLoaded) {
fetchConnectors();
}
},
[fetchConnectors, isLoaded],
);
const handleConnectorToggle = useCallback(
(connectorType: string) => {
const isSelected = selectedConnectors.includes(connectorType);
const newSelection = isSelected
? selectedConnectors.filter((type) => type !== connectorType)
: [...selectedConnectors, connectorType];
onSelectionChange?.(newSelection);
},
[selectedConnectors, onSelectionChange],
);
const handleSelectAll = useCallback(() => {
onSelectionChange?.(connectorSourceItems.map((c) => c.type));
}, [connectorSourceItems, onSelectionChange]);
const handleClearAll = useCallback(() => {
onSelectionChange?.([]);
}, [onSelectionChange]);
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<ConnectorButtonComponent
selectedConnectors={selectedConnectors}
onClick={() => setIsOpen(true)}
connectorSources={connectorSourceItems}
/>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogTitle>Select Connectors</DialogTitle>
<DialogDescription>
Choose which data sources to include in your research
</DialogDescription>
{/* Connector selection grid */}
<div className="grid grid-cols-2 gap-4 py-4">
{isLoading ? (
<div className="col-span-2 flex justify-center py-4">
<div className="animate-spin h-6 w-6 border-2 border-primary border-t-transparent rounded-full" />
</div>
) : (
connectorSourceItems.map((connector) => {
const isSelected = selectedConnectors.includes(connector.type);
return (
<div
key={connector.id}
className={`flex items-center gap-2 p-2 rounded-md border cursor-pointer transition-colors ${
isSelected
? "border-primary bg-primary/10"
: "border-border hover:border-primary/50 hover:bg-muted"
}`}
onClick={() => handleConnectorToggle(connector.type)}
role="checkbox"
aria-checked={isSelected}
tabIndex={0}
>
<div className="flex-shrink-0 w-6 h-6 flex items-center justify-center rounded-full bg-muted">
{getConnectorIcon(connector.type)}
</div>
<span className="flex-1 text-sm font-medium">
{connector.name}
</span>
{isSelected && <Check className="h-4 w-4 text-primary" />}
</div>
);
})
)}
</div>
<DialogFooter className="flex justify-between items-center">
<div className="flex gap-2">
<Button variant="outline" onClick={handleClearAll}>
Clear All
</Button>
<Button onClick={handleSelectAll}>Select All</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
},
);
ConnectorSelector.displayName = "ConnectorSelector";
const SearchModeSelector = React.memo(
({
searchMode,
onSearchModeChange,
}: {
searchMode?: "DOCUMENTS" | "CHUNKS";
onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void;
}) => {
const handleDocumentsClick = React.useCallback(() => {
onSearchModeChange?.("DOCUMENTS");
}, [onSearchModeChange]);
const handleChunksClick = React.useCallback(() => {
onSearchModeChange?.("CHUNKS");
}, [onSearchModeChange]);
return (
<div className="flex items-center gap-1 sm:gap-2">
<span className="text-xs text-muted-foreground hidden sm:block">
Scope:
</span>
<div className="flex rounded-md border border-border overflow-hidden">
<Button
variant={searchMode === "DOCUMENTS" ? "default" : "ghost"}
size="sm"
className="rounded-none border-r h-8 px-2 sm:px-3 text-xs transition-all duration-200 hover:bg-muted/80"
onClick={handleDocumentsClick}
>
<span className="hidden sm:inline">Documents</span>
<span className="sm:hidden">Docs</span>
</Button>
<Button
variant={searchMode === "CHUNKS" ? "default" : "ghost"}
size="sm"
className="rounded-none h-8 px-2 sm:px-3 text-xs transition-all duration-200 hover:bg-muted/80"
onClick={handleChunksClick}
>
Chunks
</Button>
</div>
</div>
);
},
);
SearchModeSelector.displayName = "SearchModeSelector";
const ResearchModeSelector = React.memo(
({
researchMode,
onResearchModeChange,
}: {
researchMode?: ResearchMode;
onResearchModeChange?: (mode: ResearchMode) => void;
}) => {
const handleValueChange = React.useCallback(
(value: string) => {
onResearchModeChange?.(value as ResearchMode);
},
[onResearchModeChange],
);
// Memoize mode options to prevent recreation
const modeOptions = React.useMemo(
() => [
{ value: "QNA", label: "Q&A", shortLabel: "Q&A" },
{
value: "REPORT_GENERAL",
label: "General Report",
shortLabel: "General",
},
{
value: "REPORT_DEEP",
label: "Deep Report",
shortLabel: "Deep",
},
{
value: "REPORT_DEEPER",
label: "Deeper Report",
shortLabel: "Deeper",
},
],
[],
);
return (
<div className="flex items-center gap-1 sm:gap-2">
<span className="text-xs text-muted-foreground hidden sm:block">
Mode:
</span>
<Select value={researchMode} onValueChange={handleValueChange}>
<SelectTrigger className="w-auto min-w-[80px] sm:min-w-[120px] h-8 text-xs border-border bg-background hover:bg-muted/50 transition-colors duration-200 focus:ring-2 focus:ring-primary/20">
<SelectValue placeholder="Mode" className="text-xs" />
</SelectTrigger>
<SelectContent align="end" className="min-w-[140px]">
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30">
Research Mode
</div>
{modeOptions.map((option) => (
<SelectItem
key={option.value}
value={option.value}
className="px-3 py-2 cursor-pointer hover:bg-accent/50 focus:bg-accent"
>
<span className="hidden sm:inline">{option.label}</span>
<span className="sm:hidden">{option.shortLabel}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
},
);
ResearchModeSelector.displayName = "ResearchModeSelector";
const LLMSelector = React.memo(() => {
const { llmConfigs, loading: llmLoading, error } = useLLMConfigs();
const {
preferences,
updatePreferences,
loading: preferencesLoading,
} = useLLMPreferences();
const isLoading = llmLoading || preferencesLoading;
// Memoize the selected config to avoid repeated lookups
const selectedConfig = React.useMemo(() => {
if (!preferences.fast_llm_id || !llmConfigs.length) return null;
return (
llmConfigs.find((config) => config.id === preferences.fast_llm_id) || null
);
}, [preferences.fast_llm_id, llmConfigs]);
// Memoize the display value for the trigger
const displayValue = React.useMemo(() => {
if (!selectedConfig) return null;
return (
<div className="flex items-center gap-1">
<span className="font-medium text-xs">{selectedConfig.provider}</span>
<span className="text-muted-foreground"></span>
<span className="hidden sm:inline text-muted-foreground text-xs truncate max-w-[60px]">
{selectedConfig.name}
</span>
</div>
);
}, [selectedConfig]);
const handleValueChange = React.useCallback(
(value: string) => {
const llmId = value ? parseInt(value, 10) : undefined;
updatePreferences({ fast_llm_id: llmId });
},
[updatePreferences],
);
// Loading skeleton
if (isLoading) {
return (
<div className="h-8 min-w-[100px] sm:min-w-[120px]">
<div className="h-8 rounded-md bg-muted animate-pulse flex items-center px-3">
<div className="w-3 h-3 rounded bg-muted-foreground/20 mr-2" />
<div className="h-3 w-16 rounded bg-muted-foreground/20" />
</div>
</div>
);
}
// Error state
if (error) {
return (
<div className="h-8 min-w-[100px] sm:min-w-[120px]">
<Button
variant="outline"
size="sm"
className="h-8 px-3 text-xs text-destructive border-destructive/50 hover:bg-destructive/10"
disabled
>
<span className="text-xs">Error</span>
</Button>
</div>
);
}
return (
<div className="h-8 min-w-0">
<Select
value={preferences.fast_llm_id?.toString() || ""}
onValueChange={handleValueChange}
disabled={isLoading}
>
<SelectTrigger className="h-8 w-auto min-w-[100px] sm:min-w-[120px] px-3 text-xs border-border bg-background hover:bg-muted/50 transition-colors duration-200 focus:ring-2 focus:ring-primary/20">
<div className="flex items-center gap-2 min-w-0">
<Zap className="h-3 w-3 text-primary flex-shrink-0" />
<SelectValue placeholder="Fast LLM" className="text-xs">
{displayValue || (
<span className="text-muted-foreground">Select LLM</span>
)}
</SelectValue>
</div>
</SelectTrigger>
<SelectContent align="end" className="w-[300px] max-h-[400px]">
<div className="px-3 py-2 text-xs font-medium text-muted-foreground border-b bg-muted/30">
<div className="flex items-center gap-2">
<Zap className="h-3 w-3" />
Fast LLM Selection
</div>
</div>
{llmConfigs.length === 0 ? (
<div className="px-4 py-6 text-center">
<div className="mx-auto w-12 h-12 rounded-full bg-muted flex items-center justify-center mb-3">
<Brain className="h-5 w-5 text-muted-foreground" />
</div>
<h4 className="text-sm font-medium mb-1">
No LLM configurations
</h4>
<p className="text-xs text-muted-foreground mb-3">
Configure AI models to get started
</p>
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={() => window.open("/settings", "_blank")}
>
Open Settings
</Button>
</div>
) : (
<div className="py-1">
{llmConfigs.map((config) => (
<SelectItem
key={config.id}
value={config.id.toString()}
className="px-3 py-2 cursor-pointer hover:bg-accent/50 focus:bg-accent"
>
<div className="flex items-center justify-between w-full min-w-0">
<div className="flex items-center gap-3 min-w-0 flex-1">
<div className="flex h-8 w-8 items-center justify-center rounded-md bg-primary/10 flex-shrink-0">
<Brain className="h-4 w-4 text-primary" />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm truncate">
{config.name}
</span>
<Badge
variant="outline"
className="text-xs px-1.5 py-0.5 flex-shrink-0"
>
{config.provider}
</Badge>
</div>
<p className="text-xs text-muted-foreground font-mono truncate">
{config.model_name}
</p>
</div>
</div>
{preferences.fast_llm_id === config.id && (
<div className="flex h-5 w-5 items-center justify-center rounded-full bg-primary ml-2 flex-shrink-0">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</SelectItem>
))}
</div>
)}
</SelectContent>
</Select>
</div>
);
});
LLMSelector.displayName = "LLMSelector";
const CustomChatInputOptions = React.memo(
({
onDocumentSelectionChange,
selectedDocuments,
onConnectorSelectionChange,
selectedConnectors,
searchMode,
onSearchModeChange,
researchMode,
onResearchModeChange,
}: {
onDocumentSelectionChange?: (documents: Document[]) => void;
selectedDocuments?: Document[];
onConnectorSelectionChange?: (connectorTypes: string[]) => void;
selectedConnectors?: string[];
searchMode?: "DOCUMENTS" | "CHUNKS";
onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void;
researchMode?: ResearchMode;
onResearchModeChange?: (mode: ResearchMode) => void;
}) => {
// Memoize the loading fallback to prevent recreation
const loadingFallback = React.useMemo(
() => (
<div className="h-8 min-w-[100px] animate-pulse bg-muted rounded-md" />
),
[],
);
return (
<div className="flex flex-wrap gap-2 sm:gap-3 items-center justify-start">
<Suspense fallback={loadingFallback}>
<DocumentSelector
onSelectionChange={onDocumentSelectionChange}
selectedDocuments={selectedDocuments}
/>
</Suspense>
<Suspense fallback={loadingFallback}>
<ConnectorSelector
onSelectionChange={onConnectorSelectionChange}
selectedConnectors={selectedConnectors}
/>
</Suspense>
<SearchModeSelector
searchMode={searchMode}
onSearchModeChange={onSearchModeChange}
/>
<ResearchModeSelector
researchMode={researchMode}
onResearchModeChange={onResearchModeChange}
/>
<LLMSelector />
</div>
);
},
);
CustomChatInputOptions.displayName = "CustomChatInputOptions";
export const ChatInputUI = React.memo(
({
onDocumentSelectionChange,
selectedDocuments,
onConnectorSelectionChange,
selectedConnectors,
searchMode,
onSearchModeChange,
researchMode,
onResearchModeChange,
}: {
onDocumentSelectionChange?: (documents: Document[]) => void;
selectedDocuments?: Document[];
onConnectorSelectionChange?: (connectorTypes: string[]) => void;
selectedConnectors?: string[];
searchMode?: "DOCUMENTS" | "CHUNKS";
onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void;
researchMode?: ResearchMode;
onResearchModeChange?: (mode: ResearchMode) => void;
}) => {
return (
<ChatInput>
<ChatInput.Form className="flex gap-2">
<ChatInput.Field className="flex-1" />
<ChatInput.Submit />
</ChatInput.Form>
<CustomChatInputOptions
onDocumentSelectionChange={onDocumentSelectionChange}
selectedDocuments={selectedDocuments}
onConnectorSelectionChange={onConnectorSelectionChange}
selectedConnectors={selectedConnectors}
searchMode={searchMode}
onSearchModeChange={onSearchModeChange}
researchMode={researchMode}
onResearchModeChange={onResearchModeChange}
/>
</ChatInput>
);
},
);
ChatInputUI.displayName = "ChatInputUI";

View file

@ -0,0 +1,55 @@
"use client";
import React from "react";
import {
ChatSection as LlamaIndexChatSection,
ChatHandler,
} from "@llamaindex/chat-ui";
import { Document } from "@/hooks/use-documents";
import { ChatInputUI } from "@/components/chat/ChatInputGroup";
import { ResearchMode } from "@/components/chat";
import { ChatMessagesUI } from "@/components/chat/ChatMessages";
interface ChatInterfaceProps {
handler: ChatHandler;
onDocumentSelectionChange?: (documents: Document[]) => void;
selectedDocuments?: Document[];
onConnectorSelectionChange?: (connectorTypes: string[]) => void;
selectedConnectors?: string[];
searchMode?: "DOCUMENTS" | "CHUNKS";
onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void;
researchMode?: ResearchMode;
onResearchModeChange?: (mode: ResearchMode) => void;
}
export default function ChatInterface({
handler,
onDocumentSelectionChange,
selectedDocuments = [],
onConnectorSelectionChange,
selectedConnectors = [],
searchMode,
onSearchModeChange,
researchMode,
onResearchModeChange,
}: ChatInterfaceProps) {
return (
<LlamaIndexChatSection handler={handler} className="flex h-full">
<div className="flex flex-1 flex-col">
<ChatMessagesUI />
<div className="border-t p-4">
<ChatInputUI
onDocumentSelectionChange={onDocumentSelectionChange}
selectedDocuments={selectedDocuments}
onConnectorSelectionChange={onConnectorSelectionChange}
selectedConnectors={selectedConnectors}
searchMode={searchMode}
onSearchModeChange={onSearchModeChange}
researchMode={researchMode}
onResearchModeChange={onResearchModeChange}
/>
</div>
</div>
</LlamaIndexChatSection>
);
}

View file

@ -0,0 +1,78 @@
"use client";
import React from "react";
import {
ChatMessage as LlamaIndexChatMessage,
ChatMessages as LlamaIndexChatMessages,
Message,
useChatUI,
} from "@llamaindex/chat-ui";
import TerminalDisplay from "@/components/chat/ChatTerminal";
import ChatSourcesDisplay from "@/components/chat/ChatSources";
import { CitationDisplay } from "@/components/chat/ChatCitation";
import { ChatFurtherQuestions } from "@/components/chat/ChatFurtherQuestions";
export function ChatMessagesUI() {
const { messages } = useChatUI();
return (
<LlamaIndexChatMessages className="flex-1">
<LlamaIndexChatMessages.Empty heading="Welcome to Surfsense!" subheading="Ask me anything from your documents" />
<LlamaIndexChatMessages.List className="p-4">
{messages.map((message, index) => (
<ChatMessageUI
key={`Message-${index}`}
message={message}
isLast={index === messages.length - 1}
/>
))}
</LlamaIndexChatMessages.List>
<LlamaIndexChatMessages.Loading />
</LlamaIndexChatMessages>
);
}
function ChatMessageUI({
message,
isLast,
}: {
message: Message;
isLast: boolean;
}) {
const bottomRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
if (isLast && bottomRef.current) {
bottomRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [message]);
return (
<LlamaIndexChatMessage
message={message}
isLast={isLast}
className="flex flex-col "
>
{message.role === "assistant" ? (
<div className="flex-1 flex flex-col space-y-4">
<TerminalDisplay message={message} open={isLast} />
<ChatSourcesDisplay message={message} />
<LlamaIndexChatMessage.Content className="flex-1">
<LlamaIndexChatMessage.Content.Markdown
citationComponent={CitationDisplay}
/>
</LlamaIndexChatMessage.Content>
<div ref={bottomRef} />
<div className="flex flex-row justify-end gap-2">
{isLast && <ChatFurtherQuestions message={message} />}
<LlamaIndexChatMessage.Actions className="flex-1 flex-col" />
</div>
</div>
) : (
<LlamaIndexChatMessage.Content className="flex-1">
<LlamaIndexChatMessage.Content.Markdown />
</LlamaIndexChatMessage.Content>
)}
</LlamaIndexChatMessage>
);
}

View file

@ -0,0 +1,224 @@
"use client";
import { useState } from "react";
import { getAnnotationData, Message } from "@llamaindex/chat-ui";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ExternalLink, FileText, Globe } from "lucide-react";
import { IconBrandGithub } from "@tabler/icons-react";
interface Source {
id: string;
title: string;
description: string;
url: string;
}
interface SourceGroup {
id: number;
name: string;
type: string;
sources: Source[];
}
// New interfaces for the updated data format
interface NodeMetadata {
title: string;
source_type: string;
group_name: string;
}
interface SourceNode {
id: string;
text: string;
url: string;
metadata: NodeMetadata;
}
interface NodesResponse {
nodes: SourceNode[];
}
function getSourceIcon(type: string) {
switch (type) {
case "USER_SELECTED_GITHUB_CONNECTOR":
case "GITHUB_CONNECTOR":
return <IconBrandGithub className="h-4 w-4" />;
case "USER_SELECTED_NOTION_CONNECTOR":
case "NOTION_CONNECTOR":
return <FileText className="h-4 w-4" />;
case "USER_SELECTED_FILE":
case "FILE":
return <FileText className="h-4 w-4" />;
default:
return <Globe className="h-4 w-4" />;
}
}
function SourceCard({ source }: { source: Source }) {
const hasUrl = source.url && source.url.trim() !== "";
return (
<Card className="mb-3">
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-sm md:text-base font-medium leading-tight">
{source.title}
</CardTitle>
{hasUrl && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 md:h-8 md:w-8 p-0 flex-shrink-0"
onClick={() => window.open(source.url, "_blank")}
>
<ExternalLink className="h-3 w-3 md:h-4 md:w-4" />
</Button>
)}
</div>
</CardHeader>
<CardContent className="pt-0">
<CardDescription className="text-xs md:text-sm line-clamp-3 md:line-clamp-4 leading-relaxed">
{source.description}
</CardDescription>
</CardContent>
</Card>
);
}
export default function ChatSourcesDisplay({ message }: { message: Message }) {
const [open, setOpen] = useState(false);
const annotations = getAnnotationData(message, "sources");
// Transform the new data format to the expected SourceGroup format
const sourceGroups: SourceGroup[] = [];
if (Array.isArray(annotations) && annotations.length > 0) {
// Extract all nodes from the response
const allNodes: SourceNode[] = [];
annotations.forEach((item) => {
if (
item &&
typeof item === "object" &&
"nodes" in item &&
Array.isArray(item.nodes)
) {
allNodes.push(...item.nodes);
}
});
// Group nodes by source_type
const groupedByType = allNodes.reduce(
(acc, node) => {
const sourceType = node.metadata.source_type;
if (!acc[sourceType]) {
acc[sourceType] = [];
}
acc[sourceType].push(node);
return acc;
},
{} as Record<string, SourceNode[]>,
);
// Convert grouped nodes to SourceGroup format
Object.entries(groupedByType).forEach(([sourceType, nodes], index) => {
if (nodes.length > 0) {
const firstNode = nodes[0];
sourceGroups.push({
id: index + 100, // Generate unique ID
name: firstNode.metadata.group_name,
type: sourceType,
sources: nodes.map((node) => ({
id: node.id,
title: node.metadata.title,
description: node.text,
url: node.url || "",
})),
});
}
});
}
if (sourceGroups.length === 0) {
return null;
}
const totalSources = sourceGroups.reduce(
(acc, group) => acc + group.sources.length,
0,
);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="w-fit">
<FileText className="h-4 w-4 mr-2" />
View Sources ({totalSources})
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl md:h-[80vh] h-[90vh] w-[95vw] md:w-auto flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle>Sources</DialogTitle>
</DialogHeader>
<Tabs
defaultValue={sourceGroups[0]?.type}
className="flex-1 flex flex-col min-h-0"
>
<div className="flex-shrink-0 w-full overflow-x-auto">
<TabsList className="flex w-max min-w-full">
{sourceGroups.map((group) => (
<TabsTrigger
key={group.type}
value={group.type}
className="flex items-center gap-2 whitespace-nowrap px-3 md:px-4"
>
{getSourceIcon(group.type)}
<span className="truncate max-w-[100px] md:max-w-none">
{group.name}
</span>
<Badge
variant="secondary"
className="ml-1 h-5 text-xs flex-shrink-0"
>
{group.sources.length}
</Badge>
</TabsTrigger>
))}
</TabsList>
</div>
{sourceGroups.map((group) => (
<TabsContent
key={group.type}
value={group.type}
className="flex-1 min-h-0 mt-4"
>
<div className="h-full overflow-y-auto pr-2">
<div className="space-y-3">
{group.sources.map((source) => (
<SourceCard key={source.id} source={source} />
))}
</div>
</div>
</TabsContent>
))}
</Tabs>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,115 @@
"use client";
import React from "react";
import { getAnnotationData, Message } from "@llamaindex/chat-ui";
export default function TerminalDisplay({
message,
open,
}: {
message: Message;
open: boolean;
}) {
const [isCollapsed, setIsCollapsed] = React.useState(!open);
const bottomRef = React.useRef<HTMLDivElement>(null);
// Get the last assistant message that's not being typed
if (!message) {
return <></>;
}
interface TerminalInfo {
id: number;
text: string;
type: string;
}
const events = getAnnotationData(message, "TERMINAL_INFO") as TerminalInfo[];
if (events.length === 0) {
return <></>;
}
React.useEffect(() => {
if (bottomRef.current) {
bottomRef.current.scrollTo({
top: bottomRef.current.scrollHeight,
behavior: "smooth",
});
}
}, [events]);
return (
<div className="bg-gray-900 rounded-lg border border-gray-700 overflow-hidden font-mono text-sm shadow-lg">
{/* Terminal Header */}
<div
className="bg-gray-800 px-4 py-2 flex items-center gap-2 border-b border-gray-700 cursor-pointer hover:bg-gray-750 transition-colors"
onClick={() => setIsCollapsed(!isCollapsed)}
>
<div className="flex gap-2">
<div className="w-3 h-3 rounded-full bg-red-500"></div>
<div className="w-3 h-3 rounded-full bg-yellow-500"></div>
<div className="w-3 h-3 rounded-full bg-green-500"></div>
</div>
<div className="text-gray-400 text-xs ml-2 flex-1">
Agent Process Terminal ({events.length} events)
</div>
<div className="text-gray-400">
{isCollapsed ? (
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
) : (
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 15l7-7 7 7"
/>
</svg>
)}
</div>
</div>
{/* Terminal Content */}
{!isCollapsed && (
<div
ref={bottomRef}
className="h-64 overflow-y-auto p-4 space-y-1 bg-gray-900"
>
{events.map((event, index) => (
<div key={`${event.id}-${index}`} className="text-green-400">
<span className="text-blue-400">$</span>
<span className="text-yellow-400 ml-2">[{event.type || ""}]</span>
<span className="text-gray-300 ml-4 mt-1 pl-2 border-l-2 border-gray-600">
{event.text || ""}...
</span>
</div>
))}
{events.length === 0 && (
<div className="text-gray-500 italic">
No agent events to display...
</div>
)}
</div>
)}
</div>
);
}

View file

@ -0,0 +1,502 @@
"use client";
import * as React from "react";
import {
ColumnDef,
ColumnFiltersState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
SortingState,
useReactTable,
VisibilityState,
} from "@tanstack/react-table";
import { ArrowUpDown, Calendar, FileText, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Document, DocumentType } from "@/hooks/use-documents";
interface DocumentsDataTableProps {
documents: Document[];
onSelectionChange: (documents: Document[]) => void;
onDone: () => void;
initialSelectedDocuments?: Document[];
}
const DOCUMENT_TYPES: (DocumentType | "ALL")[] = [
"ALL",
"FILE",
"EXTENSION",
"CRAWLED_URL",
"YOUTUBE_VIDEO",
"SLACK_CONNECTOR",
"NOTION_CONNECTOR",
"GITHUB_CONNECTOR",
"LINEAR_CONNECTOR",
"DISCORD_CONNECTOR",
];
const getDocumentTypeColor = (type: DocumentType) => {
const colors = {
FILE: "bg-blue-50 text-blue-700 border-blue-200",
EXTENSION: "bg-green-50 text-green-700 border-green-200",
CRAWLED_URL: "bg-purple-50 text-purple-700 border-purple-200",
YOUTUBE_VIDEO: "bg-red-50 text-red-700 border-red-200",
SLACK_CONNECTOR: "bg-yellow-50 text-yellow-700 border-yellow-200",
NOTION_CONNECTOR: "bg-indigo-50 text-indigo-700 border-indigo-200",
GITHUB_CONNECTOR: "bg-gray-50 text-gray-700 border-gray-200",
LINEAR_CONNECTOR: "bg-pink-50 text-pink-700 border-pink-200",
DISCORD_CONNECTOR: "bg-violet-50 text-violet-700 border-violet-200",
};
return colors[type] || "bg-gray-50 text-gray-700 border-gray-200";
};
const columns: ColumnDef<Document>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
size: 40,
},
{
accessorKey: "title",
header: ({ column }) => (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="h-8 px-1 sm:px-2 font-medium text-left justify-start"
>
<FileText className="mr-1 sm:mr-2 h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
<span className="hidden sm:inline">Title</span>
<span className="sm:hidden">Doc</span>
<ArrowUpDown className="ml-1 sm:ml-2 h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
</Button>
),
cell: ({ row }) => {
const title = row.getValue("title") as string;
return (
<div
className="font-medium max-w-[120px] sm:max-w-[250px] truncate text-xs sm:text-sm"
title={title}
>
{title}
</div>
);
},
},
{
accessorKey: "document_type",
header: "Type",
cell: ({ row }) => {
const type = row.getValue("document_type") as DocumentType;
return (
<Badge
variant="outline"
className={`${getDocumentTypeColor(
type,
)} text-[10px] sm:text-xs px-1 sm:px-2`}
>
<span className="hidden sm:inline">{type.replace(/_/g, " ")}</span>
<span className="sm:hidden">{type.split("_")[0]}</span>
</Badge>
);
},
size: 80,
meta: {
className: "hidden sm:table-cell",
},
},
{
accessorKey: "content",
header: "Preview",
cell: ({ row }) => {
const content = row.getValue("content") as string;
return (
<div
className="text-muted-foreground max-w-[150px] sm:max-w-[350px] truncate text-[10px] sm:text-sm"
title={content}
>
<span className="sm:hidden">{content.substring(0, 30)}...</span>
<span className="hidden sm:inline">
{content.substring(0, 100)}...
</span>
</div>
);
},
enableSorting: false,
meta: {
className: "hidden md:table-cell",
},
},
{
accessorKey: "created_at",
header: ({ column }) => (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="h-8 px-1 sm:px-2 font-medium"
>
<Calendar className="mr-1 sm:mr-2 h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
<span className="hidden sm:inline">Created</span>
<span className="sm:hidden">Date</span>
<ArrowUpDown className="ml-1 sm:ml-2 h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
</Button>
),
cell: ({ row }) => {
const date = new Date(row.getValue("created_at"));
return (
<div className="text-xs sm:text-sm whitespace-nowrap">
<span className="hidden sm:inline">
{date.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})}
</span>
<span className="sm:hidden">
{date.toLocaleDateString("en-US", {
month: "numeric",
day: "numeric",
})}
</span>
</div>
);
},
size: 80,
},
];
export function DocumentsDataTable({
documents,
onSelectionChange,
onDone,
initialSelectedDocuments = [],
}: DocumentsDataTableProps) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[],
);
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [documentTypeFilter, setDocumentTypeFilter] = React.useState<
DocumentType | "ALL"
>("ALL");
// Memoize initial row selection to prevent infinite loops
const initialRowSelection = React.useMemo(() => {
if (!documents.length || !initialSelectedDocuments.length) return {};
const selection: Record<string, boolean> = {};
initialSelectedDocuments.forEach((selectedDoc) => {
const docIndex = documents.findIndex((doc) => doc.id === selectedDoc.id);
if (docIndex !== -1) {
selection[docIndex.toString()] = true;
}
});
return selection;
}, [documents, initialSelectedDocuments]);
const [rowSelection, setRowSelection] = React.useState<
Record<string, boolean>
>({});
// Only update row selection when initialRowSelection actually changes and is not empty
React.useEffect(() => {
const hasChanges =
JSON.stringify(rowSelection) !== JSON.stringify(initialRowSelection);
if (hasChanges && Object.keys(initialRowSelection).length > 0) {
setRowSelection(initialRowSelection);
}
}, [initialRowSelection]);
// Initialize row selection on mount
React.useEffect(() => {
if (
Object.keys(rowSelection).length === 0 &&
Object.keys(initialRowSelection).length > 0
) {
setRowSelection(initialRowSelection);
}
}, []);
const filteredDocuments = React.useMemo(() => {
if (documentTypeFilter === "ALL") return documents;
return documents.filter((doc) => doc.document_type === documentTypeFilter);
}, [documents, documentTypeFilter]);
const table = useReactTable({
data: filteredDocuments,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
initialState: { pagination: { pageSize: 10 } },
state: { sorting, columnFilters, columnVisibility, rowSelection },
});
React.useEffect(() => {
const selectedRows = table.getFilteredSelectedRowModel().rows;
const selectedDocuments = selectedRows.map((row) => row.original);
onSelectionChange(selectedDocuments);
}, [rowSelection, onSelectionChange, table]);
const handleClearAll = () => setRowSelection({});
const handleSelectPage = () => {
const currentPageRows = table.getRowModel().rows;
const newSelection = { ...rowSelection };
currentPageRows.forEach((row) => {
newSelection[row.id] = true;
});
setRowSelection(newSelection);
};
const handleSelectAllFiltered = () => {
const allFilteredRows = table.getFilteredRowModel().rows;
const newSelection: Record<string, boolean> = {};
allFilteredRows.forEach((row) => {
newSelection[row.id] = true;
});
setRowSelection(newSelection);
};
const selectedCount = table.getFilteredSelectedRowModel().rows.length;
const totalFiltered = table.getFilteredRowModel().rows.length;
return (
<div className="flex flex-col h-full space-y-3 md:space-y-4">
{/* Header Controls */}
<div className="space-y-3 md:space-y-4 flex-shrink-0">
{/* Search and Filter Row */}
<div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
<div className="relative flex-1 max-w-full sm:max-w-sm">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search documents..."
value={
(table.getColumn("title")?.getFilterValue() as string) ?? ""
}
onChange={(event) =>
table.getColumn("title")?.setFilterValue(event.target.value)
}
className="pl-10 text-sm"
/>
</div>
<Select
value={documentTypeFilter}
onValueChange={(value) =>
setDocumentTypeFilter(value as DocumentType | "ALL")
}
>
<SelectTrigger className="w-full sm:w-[180px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{DOCUMENT_TYPES.map((type) => (
<SelectItem key={type} value={type}>
{type === "ALL" ? "All Types" : type.replace(/_/g, " ")}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Action Controls Row */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div className="flex flex-col sm:flex-row sm:items-center gap-2">
<span className="text-sm text-muted-foreground whitespace-nowrap">
{selectedCount} of {totalFiltered} selected
</span>
<div className="hidden sm:block h-4 w-px bg-border mx-2" />
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="ghost"
size="sm"
onClick={handleClearAll}
disabled={selectedCount === 0}
className="text-xs sm:text-sm"
>
Clear All
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleSelectPage}
className="text-xs sm:text-sm"
>
Select Page
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleSelectAllFiltered}
className="text-xs sm:text-sm hidden sm:inline-flex"
>
Select All Filtered
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleSelectAllFiltered}
className="text-xs sm:hidden"
>
Select All
</Button>
</div>
</div>
<Button
onClick={onDone}
disabled={selectedCount === 0}
className="w-full sm:w-auto sm:min-w-[100px]"
>
Done ({selectedCount})
</Button>
</div>
</div>
{/* Table Container */}
<div className="border rounded-lg flex-1 min-h-0 overflow-hidden bg-background">
<div className="overflow-auto h-full">
<Table>
<TableHeader className="sticky top-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 z-10">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="border-b">
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className="h-12 text-xs sm:text-sm"
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className="hover:bg-muted/30"
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="py-3 text-xs sm:text-sm"
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-32 text-center text-muted-foreground text-sm"
>
No documents found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
{/* Footer Pagination */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-xs sm:text-sm text-muted-foreground border-t pt-3 md:pt-4 flex-shrink-0">
<div className="text-center sm:text-left">
Showing{" "}
{table.getState().pagination.pageIndex *
table.getState().pagination.pageSize +
1}{" "}
to{" "}
{Math.min(
(table.getState().pagination.pageIndex + 1) *
table.getState().pagination.pageSize,
table.getFilteredRowModel().rows.length,
)}{" "}
of {table.getFilteredRowModel().rows.length} documents
</div>
<div className="flex items-center justify-center sm:justify-end space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="text-xs sm:text-sm"
>
Previous
</Button>
<div className="flex items-center space-x-1 text-xs sm:text-sm">
<span>Page</span>
<strong>{table.getState().pagination.pageIndex + 1}</strong>
<span>of</span>
<strong>{table.getPageCount()}</strong>
</div>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="text-xs sm:text-sm"
>
Next
</Button>
</div>
</div>
</div>
);
}

View file

@ -1,23 +0,0 @@
// Connector sources
export const connectorSourcesMenu = [
{
id: 1,
name: "Crawled URL",
type: "CRAWLED_URL",
},
{
id: 2,
name: "File",
type: "FILE",
},
{
id: 3,
name: "Extension",
type: "EXTENSION",
},
{
id: 4,
name: "Youtube Video",
type: "YOUTUBE_VIDEO",
}
];