Merge pull request #438 from langflow-ai/feat/chat-filter-context
update chat page to use a different filter for every conversation
This commit is contained in:
commit
aa4567889b
20 changed files with 3335 additions and 3233 deletions
|
|
@ -206,9 +206,7 @@ function AuthCallbackContent() {
|
|||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() =>
|
||||
router.push(isAppAuth ? "/login" : "/settings")
|
||||
}
|
||||
onClick={() => router.push(isAppAuth ? "/login" : "/settings")}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ interface AssistantMessageProps {
|
|||
isInactive?: boolean;
|
||||
animate?: boolean;
|
||||
delay?: number;
|
||||
isInitialGreeting?: boolean;
|
||||
}
|
||||
|
||||
export function AssistantMessage({
|
||||
|
|
@ -35,6 +36,7 @@ export function AssistantMessage({
|
|||
isInactive = false,
|
||||
animate = true,
|
||||
delay = 0.2,
|
||||
isInitialGreeting = false,
|
||||
}: AssistantMessageProps) {
|
||||
return (
|
||||
<motion.div
|
||||
|
|
@ -50,10 +52,32 @@ export function AssistantMessage({
|
|||
<Message
|
||||
icon={
|
||||
<div className="w-8 h-8 flex items-center justify-center flex-shrink-0 select-none">
|
||||
{/* Dog icon with bark animation when greeting */}
|
||||
<motion.div
|
||||
initial={isInitialGreeting ? { rotate: -5, y: -1 } : false}
|
||||
animate={
|
||||
isInitialGreeting
|
||||
? {
|
||||
rotate: [-5, -8, -5, 0],
|
||||
y: [-1, -2, -1, 0],
|
||||
}
|
||||
: {}
|
||||
}
|
||||
transition={
|
||||
isInitialGreeting
|
||||
? {
|
||||
duration: 0.8,
|
||||
times: [0, 0.4, 0.7, 1],
|
||||
ease: "easeInOut",
|
||||
}
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<DogIcon
|
||||
className="h-6 w-6 transition-colors duration-300"
|
||||
disabled={isCompleted || isInactive}
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
|
|
@ -76,6 +100,27 @@ export function AssistantMessage({
|
|||
onToggle={onToggle}
|
||||
/>
|
||||
<div className="relative">
|
||||
{/* Slide animation for initial greeting */}
|
||||
<motion.div
|
||||
initial={isInitialGreeting ? { opacity: 0, x: -16 } : false}
|
||||
animate={
|
||||
isInitialGreeting
|
||||
? {
|
||||
opacity: [0, 0, 1, 1],
|
||||
x: [-16, -8, 0, 0],
|
||||
}
|
||||
: {}
|
||||
}
|
||||
transition={
|
||||
isInitialGreeting
|
||||
? {
|
||||
duration: 0.8,
|
||||
times: [0, 0.3, 0.6, 1],
|
||||
ease: "easeOut",
|
||||
}
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<MarkdownRenderer
|
||||
className={cn(
|
||||
"text-sm py-1.5 transition-colors duration-300",
|
||||
|
|
@ -90,6 +135,7 @@ export function AssistantMessage({
|
|||
: content
|
||||
}
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Message>
|
||||
</motion.div>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
import { ArrowRight, Check, Funnel, Loader2, Plus } from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
|
||||
import {
|
||||
forwardRef,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useDropzone } from "react-dropzone";
|
||||
import TextareaAutosize from "react-textarea-autosize";
|
||||
import { toast } from "sonner";
|
||||
|
|
@ -13,6 +19,7 @@ import {
|
|||
} from "@/components/ui/popover";
|
||||
import { useFileDrag } from "@/hooks/use-file-drag";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useGetFiltersSearchQuery } from "../../api/queries/useGetFiltersSearchQuery";
|
||||
import type { KnowledgeFilterData } from "../_types/types";
|
||||
import { FilePreview } from "./file-preview";
|
||||
import { SelectedKnowledgeFilter } from "./selected-knowledge-filter";
|
||||
|
|
@ -27,22 +34,15 @@ interface ChatInputProps {
|
|||
loading: boolean;
|
||||
isUploading: boolean;
|
||||
selectedFilter: KnowledgeFilterData | null;
|
||||
isFilterDropdownOpen: boolean;
|
||||
availableFilters: KnowledgeFilterData[];
|
||||
filterSearchTerm: string;
|
||||
selectedFilterIndex: number;
|
||||
anchorPosition: { x: number; y: number } | null;
|
||||
parsedFilterData: { color?: FilterColor } | null;
|
||||
uploadedFile: File | null;
|
||||
onSubmit: (e: React.FormEvent) => void;
|
||||
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
onChange: (value: string) => void;
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
|
||||
onFilterSelect: (filter: KnowledgeFilterData | null) => void;
|
||||
onAtClick: () => void;
|
||||
onFilePickerClick: () => void;
|
||||
setSelectedFilter: (filter: KnowledgeFilterData | null) => void;
|
||||
setIsFilterHighlighted: (highlighted: boolean) => void;
|
||||
setIsFilterDropdownOpen: (open: boolean) => void;
|
||||
onFileSelected: (file: File | null) => void;
|
||||
}
|
||||
|
||||
|
|
@ -53,22 +53,15 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
loading,
|
||||
isUploading,
|
||||
selectedFilter,
|
||||
isFilterDropdownOpen,
|
||||
availableFilters,
|
||||
filterSearchTerm,
|
||||
selectedFilterIndex,
|
||||
anchorPosition,
|
||||
parsedFilterData,
|
||||
uploadedFile,
|
||||
onSubmit,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
onFilterSelect,
|
||||
onAtClick,
|
||||
onFilePickerClick,
|
||||
setSelectedFilter,
|
||||
setIsFilterHighlighted,
|
||||
setIsFilterDropdownOpen,
|
||||
onFileSelected,
|
||||
},
|
||||
ref,
|
||||
|
|
@ -78,6 +71,29 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
const [textareaHeight, setTextareaHeight] = useState(0);
|
||||
const isDragging = useFileDrag();
|
||||
|
||||
// Internal state for filter dropdown
|
||||
const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
|
||||
const [filterSearchTerm, setFilterSearchTerm] = useState("");
|
||||
const [selectedFilterIndex, setSelectedFilterIndex] = useState(0);
|
||||
const [anchorPosition, setAnchorPosition] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
} | null>(null);
|
||||
|
||||
// Fetch filters using the query hook
|
||||
const { data: availableFilters = [] } = useGetFiltersSearchQuery(
|
||||
filterSearchTerm,
|
||||
20,
|
||||
{ enabled: isFilterDropdownOpen },
|
||||
);
|
||||
|
||||
// Filter available filters based on search term
|
||||
const filteredFilters = useMemo(() => {
|
||||
return availableFilters.filter((filter) =>
|
||||
filter.name.toLowerCase().includes(filterSearchTerm.toLowerCase()),
|
||||
);
|
||||
}, [availableFilters, filterSearchTerm]);
|
||||
|
||||
const { getRootProps, getInputProps } = useDropzone({
|
||||
accept: {
|
||||
"application/pdf": [".pdf"],
|
||||
|
|
@ -116,6 +132,196 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
}
|
||||
};
|
||||
|
||||
const onAtClick = () => {
|
||||
if (!isFilterDropdownOpen) {
|
||||
setIsFilterDropdownOpen(true);
|
||||
setFilterSearchTerm("");
|
||||
setSelectedFilterIndex(0);
|
||||
|
||||
// Get button position for popover anchoring
|
||||
const button = document.querySelector(
|
||||
"[data-filter-button]",
|
||||
) as HTMLElement;
|
||||
if (button) {
|
||||
const rect = button.getBoundingClientRect();
|
||||
setAnchorPosition({
|
||||
x: rect.left + rect.width / 2,
|
||||
y: rect.top + rect.height / 2 - 12,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setIsFilterDropdownOpen(false);
|
||||
setAnchorPosition(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
|
||||
onFilterSelect(filter);
|
||||
|
||||
// Remove the @searchTerm from the input
|
||||
const words = input.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@")) {
|
||||
// Remove the @search term
|
||||
words.pop();
|
||||
onChange(words.join(" ") + (words.length > 0 ? " " : ""));
|
||||
}
|
||||
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
setSelectedFilterIndex(0);
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newValue = e.target.value;
|
||||
onChange(newValue); // Call parent's onChange with the string value
|
||||
|
||||
// Find if there's an @ at the start of the last word
|
||||
const words = newValue.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@")) {
|
||||
const searchTerm = lastWord.slice(1); // Remove the @
|
||||
setFilterSearchTerm(searchTerm);
|
||||
setSelectedFilterIndex(0);
|
||||
|
||||
// Only set anchor position when @ is first detected (search term is empty)
|
||||
if (searchTerm === "") {
|
||||
const getCursorPosition = (textarea: HTMLTextAreaElement) => {
|
||||
// Create a hidden div with the same styles as the textarea
|
||||
const div = document.createElement("div");
|
||||
const computedStyle = getComputedStyle(textarea);
|
||||
|
||||
// Copy all computed styles to the hidden div
|
||||
for (const style of computedStyle) {
|
||||
(div.style as unknown as Record<string, string>)[style] =
|
||||
computedStyle.getPropertyValue(style);
|
||||
}
|
||||
|
||||
// Set the div to be hidden but not un-rendered
|
||||
div.style.position = "absolute";
|
||||
div.style.visibility = "hidden";
|
||||
div.style.whiteSpace = "pre-wrap";
|
||||
div.style.wordWrap = "break-word";
|
||||
div.style.overflow = "hidden";
|
||||
div.style.height = "auto";
|
||||
div.style.width = `${textarea.getBoundingClientRect().width}px`;
|
||||
|
||||
// Get the text up to the cursor position
|
||||
const cursorPos = textarea.selectionStart || 0;
|
||||
const textBeforeCursor = textarea.value.substring(0, cursorPos);
|
||||
|
||||
// Add the text before cursor
|
||||
div.textContent = textBeforeCursor;
|
||||
|
||||
// Create a span to mark the end position
|
||||
const span = document.createElement("span");
|
||||
span.textContent = "|"; // Cursor marker
|
||||
div.appendChild(span);
|
||||
|
||||
// Add the text after cursor to handle word wrapping
|
||||
const textAfterCursor = textarea.value.substring(cursorPos);
|
||||
div.appendChild(document.createTextNode(textAfterCursor));
|
||||
|
||||
// Add the div to the document temporarily
|
||||
document.body.appendChild(div);
|
||||
|
||||
// Get positions
|
||||
const inputRect = textarea.getBoundingClientRect();
|
||||
const divRect = div.getBoundingClientRect();
|
||||
const spanRect = span.getBoundingClientRect();
|
||||
|
||||
// Calculate the cursor position relative to the input
|
||||
const x = inputRect.left + (spanRect.left - divRect.left);
|
||||
const y = inputRect.top + (spanRect.top - divRect.top);
|
||||
|
||||
// Clean up
|
||||
document.body.removeChild(div);
|
||||
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
const pos = getCursorPosition(e.target);
|
||||
setAnchorPosition(pos);
|
||||
}
|
||||
|
||||
if (!isFilterDropdownOpen) {
|
||||
setIsFilterDropdownOpen(true);
|
||||
}
|
||||
} else if (isFilterDropdownOpen) {
|
||||
// Close dropdown if @ is no longer present
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isFilterDropdownOpen) {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
setSelectedFilterIndex(0);
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setSelectedFilterIndex((prev) =>
|
||||
prev < filteredFilters.length - 1 ? prev + 1 : 0,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setSelectedFilterIndex((prev) =>
|
||||
prev > 0 ? prev - 1 : filteredFilters.length - 1,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "Enter") {
|
||||
// Check if we're at the end of an @ mention
|
||||
const cursorPos = e.currentTarget.selectionStart || 0;
|
||||
const textBeforeCursor = input.slice(0, cursorPos);
|
||||
const words = textBeforeCursor.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (
|
||||
lastWord.startsWith("@") &&
|
||||
filteredFilters[selectedFilterIndex]
|
||||
) {
|
||||
e.preventDefault();
|
||||
handleFilterSelect(filteredFilters[selectedFilterIndex]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === " ") {
|
||||
// Select filter on space if we're typing an @ mention
|
||||
const cursorPos = e.currentTarget.selectionStart || 0;
|
||||
const textBeforeCursor = input.slice(0, cursorPos);
|
||||
const words = textBeforeCursor.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (
|
||||
lastWord.startsWith("@") &&
|
||||
filteredFilters[selectedFilterIndex]
|
||||
) {
|
||||
e.preventDefault();
|
||||
handleFilterSelect(filteredFilters[selectedFilterIndex]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass through to parent onKeyDown for other key handling
|
||||
onKeyDown(e);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<form onSubmit={onSubmit} className="relative">
|
||||
|
|
@ -209,8 +415,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
<TextareaAutosize
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
onChange={onChange}
|
||||
onKeyDown={onKeyDown}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onHeightChange={(height) => setTextareaHeight(height)}
|
||||
maxRows={7}
|
||||
autoComplete="off"
|
||||
|
|
@ -336,7 +542,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
{!filterSearchTerm && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onFilterSelect(null)}
|
||||
onClick={() => handleFilterSelect(null)}
|
||||
className={`w-full text-left px-2 py-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
|
||||
selectedFilterIndex === -1 ? "bg-muted/50" : ""
|
||||
}`}
|
||||
|
|
@ -347,17 +553,11 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
)}
|
||||
</button>
|
||||
)}
|
||||
{availableFilters
|
||||
.filter((filter) =>
|
||||
filter.name
|
||||
.toLowerCase()
|
||||
.includes(filterSearchTerm.toLowerCase()),
|
||||
)
|
||||
.map((filter, index) => (
|
||||
{filteredFilters.map((filter, index) => (
|
||||
<button
|
||||
key={filter.id}
|
||||
type="button"
|
||||
onClick={() => onFilterSelect(filter)}
|
||||
onClick={() => handleFilterSelect(filter)}
|
||||
className={`w-full overflow-hidden text-left px-2 py-2 gap-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
|
||||
index === selectedFilterIndex ? "bg-muted/50" : ""
|
||||
}`}
|
||||
|
|
@ -377,12 +577,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
)}
|
||||
</button>
|
||||
))}
|
||||
{availableFilters.filter((filter) =>
|
||||
filter.name
|
||||
.toLowerCase()
|
||||
.includes(filterSearchTerm.toLowerCase()),
|
||||
).length === 0 &&
|
||||
filterSearchTerm && (
|
||||
{filteredFilters.length === 0 && filterSearchTerm && (
|
||||
<div className="px-2 py-3 text-sm text-muted-foreground">
|
||||
No filters match "{filterSearchTerm}"
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
"use client";
|
||||
|
||||
import { Loader2, Zap } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
|
||||
import { ProtectedRoute } from "@/components/protected-route";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { type EndpointType, useChat } from "@/contexts/chat-context";
|
||||
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
|
||||
import { useTask } from "@/contexts/task-context";
|
||||
import { useChatStreaming } from "@/hooks/useChatStreaming";
|
||||
import { FILE_CONFIRMATION, FILES_REGEX } from "@/lib/constants";
|
||||
|
|
@ -40,6 +39,8 @@ function ChatPage() {
|
|||
previousResponseIds,
|
||||
setPreviousResponseIds,
|
||||
placeholderConversation,
|
||||
conversationFilter,
|
||||
setConversationFilter,
|
||||
} = useChat();
|
||||
const [messages, setMessages] = useState<Message[]>([
|
||||
{
|
||||
|
|
@ -56,20 +57,9 @@ function ChatPage() {
|
|||
>(new Set());
|
||||
// previousResponseIds now comes from useChat context
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
|
||||
const [availableFilters, setAvailableFilters] = useState<
|
||||
KnowledgeFilterData[]
|
||||
>([]);
|
||||
const [filterSearchTerm, setFilterSearchTerm] = useState("");
|
||||
const [selectedFilterIndex, setSelectedFilterIndex] = useState(0);
|
||||
const [isFilterHighlighted, setIsFilterHighlighted] = useState(false);
|
||||
const [dropdownDismissed, setDropdownDismissed] = useState(false);
|
||||
const [isUserInteracting, setIsUserInteracting] = useState(false);
|
||||
const [isForkingInProgress, setIsForkingInProgress] = useState(false);
|
||||
const [anchorPosition, setAnchorPosition] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
} | null>(null);
|
||||
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
|
||||
const [waitingTooLong, setWaitingTooLong] = useState(false);
|
||||
|
||||
|
|
@ -79,8 +69,20 @@ function ChatPage() {
|
|||
|
||||
const lastLoadedConversationRef = useRef<string | null>(null);
|
||||
const { addTask } = useTask();
|
||||
const { selectedFilter, parsedFilterData, setSelectedFilter } =
|
||||
useKnowledgeFilter();
|
||||
|
||||
// Use conversation-specific filter instead of global filter
|
||||
const selectedFilter = conversationFilter;
|
||||
|
||||
// Parse the conversation filter data
|
||||
const parsedFilterData = useMemo(() => {
|
||||
if (!selectedFilter?.query_data) return null;
|
||||
try {
|
||||
return JSON.parse(selectedFilter.query_data);
|
||||
} catch (error) {
|
||||
console.error("Error parsing filter data:", error);
|
||||
return null;
|
||||
}
|
||||
}, [selectedFilter]);
|
||||
|
||||
// Use the chat streaming hook
|
||||
const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
|
||||
|
|
@ -95,7 +97,6 @@ function ChatPage() {
|
|||
setMessages((prev) => [...prev, message]);
|
||||
setLoading(false);
|
||||
setWaitingTooLong(false);
|
||||
|
||||
if (responseId) {
|
||||
cancelNudges();
|
||||
setPreviousResponseIds((prev) => ({
|
||||
|
|
@ -142,60 +143,6 @@ function ChatPage() {
|
|||
};
|
||||
}, [isStreamLoading, streamingMessage]);
|
||||
|
||||
const getCursorPosition = (textarea: HTMLTextAreaElement) => {
|
||||
// Create a hidden div with the same styles as the textarea
|
||||
const div = document.createElement("div");
|
||||
const computedStyle = getComputedStyle(textarea);
|
||||
|
||||
// Copy all computed styles to the hidden div
|
||||
for (const style of computedStyle) {
|
||||
(div.style as unknown as Record<string, string>)[style] =
|
||||
computedStyle.getPropertyValue(style);
|
||||
}
|
||||
|
||||
// Set the div to be hidden but not un-rendered
|
||||
div.style.position = "absolute";
|
||||
div.style.visibility = "hidden";
|
||||
div.style.whiteSpace = "pre-wrap";
|
||||
div.style.wordWrap = "break-word";
|
||||
div.style.overflow = "hidden";
|
||||
div.style.height = "auto";
|
||||
div.style.width = `${textarea.getBoundingClientRect().width}px`;
|
||||
|
||||
// Get the text up to the cursor position
|
||||
const cursorPos = textarea.selectionStart || 0;
|
||||
const textBeforeCursor = textarea.value.substring(0, cursorPos);
|
||||
|
||||
// Add the text before cursor
|
||||
div.textContent = textBeforeCursor;
|
||||
|
||||
// Create a span to mark the end position
|
||||
const span = document.createElement("span");
|
||||
span.textContent = "|"; // Cursor marker
|
||||
div.appendChild(span);
|
||||
|
||||
// Add the text after cursor to handle word wrapping
|
||||
const textAfterCursor = textarea.value.substring(cursorPos);
|
||||
div.appendChild(document.createTextNode(textAfterCursor));
|
||||
|
||||
// Add the div to the document temporarily
|
||||
document.body.appendChild(div);
|
||||
|
||||
// Get positions
|
||||
const inputRect = textarea.getBoundingClientRect();
|
||||
const divRect = div.getBoundingClientRect();
|
||||
const spanRect = span.getBoundingClientRect();
|
||||
|
||||
// Calculate the cursor position relative to the input
|
||||
const x = inputRect.left + (spanRect.left - divRect.left);
|
||||
const y = inputRect.top + (spanRect.top - divRect.top);
|
||||
|
||||
// Clean up
|
||||
document.body.removeChild(div);
|
||||
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
const handleEndpointChange = (newEndpoint: EndpointType) => {
|
||||
setEndpoint(newEndpoint);
|
||||
// Clear the conversation when switching endpoints to avoid response ID conflicts
|
||||
|
|
@ -317,54 +264,12 @@ function ChatPage() {
|
|||
chatInputRef.current?.clickFileInput();
|
||||
};
|
||||
|
||||
const loadAvailableFilters = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/knowledge-filter/search", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: "",
|
||||
limit: 20,
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (response.ok && result.success) {
|
||||
setAvailableFilters(result.filters);
|
||||
} else {
|
||||
console.error("Failed to load knowledge filters:", result.error);
|
||||
setAvailableFilters([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load knowledge filters:", error);
|
||||
setAvailableFilters([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
|
||||
setSelectedFilter(filter);
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
// Update conversation-specific filter
|
||||
setConversationFilter(filter);
|
||||
setIsFilterHighlighted(false);
|
||||
|
||||
// Remove the @searchTerm from the input and replace with filter pill
|
||||
const words = input.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@")) {
|
||||
// Remove the @search term
|
||||
words.pop();
|
||||
setInput(words.join(" ") + (words.length > 0 ? " " : ""));
|
||||
}
|
||||
};
|
||||
|
||||
// Reset selected index when search term changes
|
||||
useEffect(() => {
|
||||
setSelectedFilterIndex(0);
|
||||
}, []);
|
||||
|
||||
// Auto-focus the input on component mount
|
||||
useEffect(() => {
|
||||
chatInputRef.current?.focusInput();
|
||||
|
|
@ -388,6 +293,11 @@ function ChatPage() {
|
|||
setIsFilterHighlighted(false);
|
||||
setLoading(false);
|
||||
lastLoadedConversationRef.current = null;
|
||||
|
||||
// Focus input after a short delay to ensure rendering is complete
|
||||
setTimeout(() => {
|
||||
chatInputRef.current?.focusInput();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const handleFocusInput = () => {
|
||||
|
|
@ -409,8 +319,7 @@ function ChatPage() {
|
|||
// 2. It's different from the last loaded conversation AND
|
||||
// 3. User is not in the middle of an interaction
|
||||
if (
|
||||
conversationData &&
|
||||
conversationData.messages &&
|
||||
conversationData?.messages &&
|
||||
lastLoadedConversationRef.current !== conversationData.response_id &&
|
||||
!isUserInteracting &&
|
||||
!isForkingInProgress
|
||||
|
|
@ -576,6 +485,11 @@ function ChatPage() {
|
|||
...prev,
|
||||
[conversationData.endpoint]: conversationData.response_id,
|
||||
}));
|
||||
|
||||
// Focus input when loading a conversation
|
||||
setTimeout(() => {
|
||||
chatInputRef.current?.focusInput();
|
||||
}, 100);
|
||||
}
|
||||
}, [
|
||||
conversationData,
|
||||
|
|
@ -596,6 +510,11 @@ function ChatPage() {
|
|||
},
|
||||
]);
|
||||
lastLoadedConversationRef.current = null;
|
||||
|
||||
// Focus input when starting a new conversation
|
||||
setTimeout(() => {
|
||||
chatInputRef.current?.focusInput();
|
||||
}, 100);
|
||||
}
|
||||
}, [placeholderConversation, currentConversationId]);
|
||||
|
||||
|
|
@ -1035,162 +954,6 @@ function ChatPage() {
|
|||
handleSendMessage(suggestion);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
// Handle backspace for filter clearing
|
||||
if (e.key === "Backspace" && selectedFilter && input.trim() === "") {
|
||||
e.preventDefault();
|
||||
|
||||
if (isFilterHighlighted) {
|
||||
// Second backspace - remove the filter
|
||||
setSelectedFilter(null);
|
||||
setIsFilterHighlighted(false);
|
||||
} else {
|
||||
// First backspace - highlight the filter
|
||||
setIsFilterHighlighted(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isFilterDropdownOpen) {
|
||||
const filteredFilters = availableFilters.filter((filter) =>
|
||||
filter.name.toLowerCase().includes(filterSearchTerm.toLowerCase()),
|
||||
);
|
||||
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
setSelectedFilterIndex(0);
|
||||
setDropdownDismissed(true);
|
||||
|
||||
// Keep focus on the textarea so user can continue typing normally
|
||||
chatInputRef.current?.focusInput();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setSelectedFilterIndex((prev) =>
|
||||
prev < filteredFilters.length - 1 ? prev + 1 : 0,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setSelectedFilterIndex((prev) =>
|
||||
prev > 0 ? prev - 1 : filteredFilters.length - 1,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "Enter") {
|
||||
// Check if we're at the end of an @ mention (space before cursor or end of input)
|
||||
const cursorPos = e.currentTarget.selectionStart || 0;
|
||||
const textBeforeCursor = input.slice(0, cursorPos);
|
||||
const words = textBeforeCursor.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@") && filteredFilters[selectedFilterIndex]) {
|
||||
e.preventDefault();
|
||||
handleFilterSelect(filteredFilters[selectedFilterIndex]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === " ") {
|
||||
// Select filter on space if we're typing an @ mention
|
||||
const cursorPos = e.currentTarget.selectionStart || 0;
|
||||
const textBeforeCursor = input.slice(0, cursorPos);
|
||||
const words = textBeforeCursor.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@") && filteredFilters[selectedFilterIndex]) {
|
||||
e.preventDefault();
|
||||
handleFilterSelect(filteredFilters[selectedFilterIndex]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === "Enter" && !e.shiftKey && !isFilterDropdownOpen) {
|
||||
e.preventDefault();
|
||||
if (input.trim() && !loading) {
|
||||
// Trigger form submission by finding the form and calling submit
|
||||
const form = e.currentTarget.closest("form");
|
||||
if (form) {
|
||||
form.requestSubmit();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newValue = e.target.value;
|
||||
setInput(newValue);
|
||||
|
||||
// Clear filter highlight when user starts typing
|
||||
if (isFilterHighlighted) {
|
||||
setIsFilterHighlighted(false);
|
||||
}
|
||||
|
||||
// Find if there's an @ at the start of the last word
|
||||
const words = newValue.split(" ");
|
||||
const lastWord = words[words.length - 1];
|
||||
|
||||
if (lastWord.startsWith("@") && !dropdownDismissed) {
|
||||
const searchTerm = lastWord.slice(1); // Remove the @
|
||||
console.log("Setting search term:", searchTerm);
|
||||
setFilterSearchTerm(searchTerm);
|
||||
setSelectedFilterIndex(0);
|
||||
|
||||
// Only set anchor position when @ is first detected (search term is empty)
|
||||
if (searchTerm === "") {
|
||||
const pos = getCursorPosition(e.target);
|
||||
setAnchorPosition(pos);
|
||||
}
|
||||
|
||||
if (!isFilterDropdownOpen) {
|
||||
loadAvailableFilters();
|
||||
setIsFilterDropdownOpen(true);
|
||||
}
|
||||
} else if (isFilterDropdownOpen) {
|
||||
// Close dropdown if @ is no longer present
|
||||
console.log("Closing dropdown - no @ found");
|
||||
setIsFilterDropdownOpen(false);
|
||||
setFilterSearchTerm("");
|
||||
}
|
||||
|
||||
// Reset dismissed flag when user moves to a different word
|
||||
if (dropdownDismissed && !lastWord.startsWith("@")) {
|
||||
setDropdownDismissed(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onAtClick = () => {
|
||||
if (!isFilterDropdownOpen) {
|
||||
loadAvailableFilters();
|
||||
setIsFilterDropdownOpen(true);
|
||||
setFilterSearchTerm("");
|
||||
setSelectedFilterIndex(0);
|
||||
|
||||
// Get button position for popover anchoring
|
||||
const button = document.querySelector(
|
||||
"[data-filter-button]",
|
||||
) as HTMLElement;
|
||||
if (button) {
|
||||
const rect = button.getBoundingClientRect();
|
||||
setAnchorPosition({
|
||||
x: rect.left + rect.width / 2,
|
||||
y: rect.top + rect.height / 2 - 12,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setIsFilterDropdownOpen(false);
|
||||
setAnchorPosition(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Debug header - only show in debug mode */}
|
||||
|
|
@ -1313,6 +1076,11 @@ function ChatPage() {
|
|||
onFork={(e) => handleForkConversation(index, e)}
|
||||
animate={false}
|
||||
isInactive={index < messages.length - 1}
|
||||
isInitialGreeting={
|
||||
index === 0 &&
|
||||
messages.length === 1 &&
|
||||
message.content === "How can I assist?"
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
|
|
@ -1340,7 +1108,8 @@ function ChatPage() {
|
|||
<span>The server is taking longer than expected...</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This may be due to high server load. The request will timeout after 60 seconds.
|
||||
This may be due to high server load. The request will
|
||||
timeout after 60 seconds.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -1364,23 +1133,46 @@ function ChatPage() {
|
|||
loading={loading}
|
||||
isUploading={isUploading}
|
||||
selectedFilter={selectedFilter}
|
||||
isFilterDropdownOpen={isFilterDropdownOpen}
|
||||
availableFilters={availableFilters}
|
||||
filterSearchTerm={filterSearchTerm}
|
||||
selectedFilterIndex={selectedFilterIndex}
|
||||
anchorPosition={anchorPosition}
|
||||
parsedFilterData={parsedFilterData}
|
||||
uploadedFile={uploadedFile}
|
||||
onSubmit={handleSubmit}
|
||||
onChange={onChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onChange={setInput}
|
||||
onKeyDown={(e) => {
|
||||
// Handle backspace for filter clearing
|
||||
if (
|
||||
e.key === "Backspace" &&
|
||||
selectedFilter &&
|
||||
input.trim() === ""
|
||||
) {
|
||||
e.preventDefault();
|
||||
if (isFilterHighlighted) {
|
||||
// Second backspace - remove the filter
|
||||
setConversationFilter(null);
|
||||
setIsFilterHighlighted(false);
|
||||
} else {
|
||||
// First backspace - highlight the filter
|
||||
setIsFilterHighlighted(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Enter key for form submission
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (input.trim() && !loading) {
|
||||
// Trigger form submission by finding the form and calling submit
|
||||
const form = e.currentTarget.closest("form");
|
||||
if (form) {
|
||||
form.requestSubmit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
onFilterSelect={handleFilterSelect}
|
||||
onAtClick={onAtClick}
|
||||
onFilePickerClick={handleFilePickerClick}
|
||||
onFileSelected={setUploadedFile}
|
||||
setSelectedFilter={setSelectedFilter}
|
||||
setSelectedFilter={setConversationFilter}
|
||||
setIsFilterHighlighted={setIsFilterHighlighted}
|
||||
setIsFilterDropdownOpen={setIsFilterDropdownOpen}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -36,7 +36,9 @@ export function OnboardingContent({
|
|||
() => {
|
||||
// Retrieve assistant message from localStorage on mount
|
||||
if (typeof window === "undefined") return null;
|
||||
const savedMessage = localStorage.getItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
|
||||
const savedMessage = localStorage.getItem(
|
||||
ONBOARDING_ASSISTANT_MESSAGE_KEY,
|
||||
);
|
||||
if (savedMessage) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedMessage);
|
||||
|
|
@ -78,7 +80,10 @@ export function OnboardingContent({
|
|||
JSON.stringify(message),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to save assistant message to localStorage:", error);
|
||||
console.error(
|
||||
"Failed to save assistant message to localStorage:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (newResponseId) {
|
||||
|
|
|
|||
|
|
@ -201,27 +201,27 @@ export class OneDriveHandler {
|
|||
let mimeType = item.file?.mimeType;
|
||||
if (!mimeType && item.name) {
|
||||
// Infer from extension if mimeType not provided
|
||||
const ext = item.name.split('.').pop()?.toLowerCase();
|
||||
const ext = item.name.split(".").pop()?.toLowerCase();
|
||||
const mimeTypes: { [key: string]: string } = {
|
||||
pdf: 'application/pdf',
|
||||
doc: 'application/msword',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
txt: 'text/plain',
|
||||
csv: 'text/csv',
|
||||
json: 'application/json',
|
||||
xml: 'application/xml',
|
||||
html: 'text/html',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
gif: 'image/gif',
|
||||
svg: 'image/svg+xml',
|
||||
pdf: "application/pdf",
|
||||
doc: "application/msword",
|
||||
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
xls: "application/vnd.ms-excel",
|
||||
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
ppt: "application/vnd.ms-powerpoint",
|
||||
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
txt: "text/plain",
|
||||
csv: "text/csv",
|
||||
json: "application/json",
|
||||
xml: "application/xml",
|
||||
html: "text/html",
|
||||
jpg: "image/jpeg",
|
||||
jpeg: "image/jpeg",
|
||||
png: "image/png",
|
||||
gif: "image/gif",
|
||||
svg: "image/svg+xml",
|
||||
};
|
||||
mimeType = mimeTypes[ext || ''] || 'application/octet-stream';
|
||||
mimeType = mimeTypes[ext || ""] || "application/octet-stream";
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ const DogIcon = ({ disabled = false, stroke, ...props }: DogIconProps) => {
|
|||
fill={fillColor}
|
||||
{...props}
|
||||
>
|
||||
<title>Dog Icon</title>
|
||||
<path d="M8 18H2V16H8V18Z" />
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
|
|
@ -58,7 +59,9 @@ const DogIcon = ({ disabled = false, stroke, ...props }: DogIconProps) => {
|
|||
viewBox="0 0 105 77"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<title>Dog Icon</title>
|
||||
<defs>
|
||||
<style dangerouslySetInnerHTML={{ __html: animationCSS }} />
|
||||
</defs>
|
||||
|
|
|
|||
|
|
@ -152,7 +152,6 @@ export function Navigation({
|
|||
}
|
||||
};
|
||||
|
||||
|
||||
const handleDeleteConversation = (
|
||||
conversation: ChatConversation,
|
||||
event?: React.MouseEvent,
|
||||
|
|
@ -373,18 +372,19 @@ export function Navigation({
|
|||
<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) => (
|
||||
[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" : "")}
|
||||
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 ? (
|
||||
<div className="text-[13px] text-muted-foreground py-2 pl-3">
|
||||
|
|
@ -420,7 +420,9 @@ export function Navigation({
|
|||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
disabled={
|
||||
loading || isConversationsLoading || deleteSessionMutation.isPending
|
||||
loading ||
|
||||
isConversationsLoading ||
|
||||
deleteSessionMutation.isPending
|
||||
}
|
||||
asChild
|
||||
>
|
||||
|
|
|
|||
|
|
@ -17,10 +17,8 @@ const Toaster = ({ ...props }: ToasterProps) => {
|
|||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "!text-muted-foreground",
|
||||
actionButton:
|
||||
"!bg-primary !text-primary-foreground",
|
||||
cancelButton:
|
||||
"!bg-muted !text-muted-foreground",
|
||||
actionButton: "!bg-primary !text-primary-foreground",
|
||||
cancelButton: "!bg-muted !text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
|
|
@ -25,11 +25,22 @@ interface ConversationMessage {
|
|||
response_id?: string;
|
||||
}
|
||||
|
||||
interface KnowledgeFilter {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
query_data: string;
|
||||
owner: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface ConversationData {
|
||||
messages: ConversationMessage[];
|
||||
endpoint: EndpointType;
|
||||
response_id: string;
|
||||
title: string;
|
||||
filter?: KnowledgeFilter | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
|
@ -65,6 +76,8 @@ interface ChatContextType {
|
|||
setPlaceholderConversation: (conversation: ConversationData | null) => void;
|
||||
conversationLoaded: boolean;
|
||||
setConversationLoaded: (loaded: boolean) => void;
|
||||
conversationFilter: KnowledgeFilter | null;
|
||||
setConversationFilter: (filter: KnowledgeFilter | null) => void;
|
||||
}
|
||||
|
||||
const ChatContext = createContext<ChatContextType | undefined>(undefined);
|
||||
|
|
@ -92,6 +105,8 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
const [placeholderConversation, setPlaceholderConversation] =
|
||||
useState<ConversationData | null>(null);
|
||||
const [conversationLoaded, setConversationLoaded] = useState(false);
|
||||
const [conversationFilter, setConversationFilterState] =
|
||||
useState<KnowledgeFilter | null>(null);
|
||||
|
||||
// Debounce refresh requests to prevent excessive reloads
|
||||
const refreshTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
|
@ -129,17 +144,31 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
setRefreshTriggerSilent((prev) => prev + 1);
|
||||
}, []);
|
||||
|
||||
const loadConversation = useCallback((conversation: ConversationData) => {
|
||||
const loadConversation = useCallback(
|
||||
(conversation: ConversationData) => {
|
||||
setCurrentConversationId(conversation.response_id);
|
||||
setEndpoint(conversation.endpoint);
|
||||
// Store the full conversation data for the chat page to use
|
||||
setConversationData(conversation);
|
||||
// Load the filter if one exists for this conversation
|
||||
// Only update the filter if this is a different conversation (to preserve user's filter selection)
|
||||
setConversationFilterState((currentFilter) => {
|
||||
// If we're loading a different conversation, load its filter
|
||||
// Otherwise keep the current filter (don't reset it when conversation refreshes)
|
||||
const isDifferentConversation =
|
||||
conversation.response_id !== conversationData?.response_id;
|
||||
return isDifferentConversation
|
||||
? conversation.filter || null
|
||||
: currentFilter;
|
||||
});
|
||||
// Clear placeholder when loading a real conversation
|
||||
setPlaceholderConversation(null);
|
||||
setConversationLoaded(true);
|
||||
// Clear conversation docs to prevent duplicates when switching conversations
|
||||
setConversationDocs([]);
|
||||
}, []);
|
||||
},
|
||||
[conversationData?.response_id],
|
||||
);
|
||||
|
||||
const startNewConversation = useCallback(() => {
|
||||
// Clear current conversation data and reset state
|
||||
|
|
@ -148,6 +177,8 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
setConversationData(null);
|
||||
setConversationDocs([]);
|
||||
setConversationLoaded(false);
|
||||
// Clear the filter when starting a new conversation
|
||||
setConversationFilterState(null);
|
||||
|
||||
// Create a temporary placeholder conversation to show in sidebar
|
||||
const placeholderConversation: ConversationData = {
|
||||
|
|
@ -198,6 +229,21 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
[endpoint],
|
||||
);
|
||||
|
||||
const setConversationFilter = useCallback(
|
||||
(filter: KnowledgeFilter | null) => {
|
||||
setConversationFilterState(filter);
|
||||
// Update the conversation data to include the filter
|
||||
setConversationData((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
filter,
|
||||
};
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const value = useMemo<ChatContextType>(
|
||||
() => ({
|
||||
endpoint,
|
||||
|
|
@ -221,6 +267,8 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
setPlaceholderConversation,
|
||||
conversationLoaded,
|
||||
setConversationLoaded,
|
||||
conversationFilter,
|
||||
setConversationFilter,
|
||||
}),
|
||||
[
|
||||
endpoint,
|
||||
|
|
@ -239,7 +287,8 @@ export function ChatProvider({ children }: ChatProviderProps) {
|
|||
clearConversationDocs,
|
||||
placeholderConversation,
|
||||
conversationLoaded,
|
||||
setConversationLoaded,
|
||||
conversationFilter,
|
||||
setConversationFilter,
|
||||
],
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -466,8 +466,13 @@ export function useChatStreaming({
|
|||
}
|
||||
|
||||
// Check if we got any content at all
|
||||
if (!hasReceivedData || (!currentContent && currentFunctionCalls.length === 0)) {
|
||||
throw new Error("No response received from the server. Please try again.");
|
||||
if (
|
||||
!hasReceivedData ||
|
||||
(!currentContent && currentFunctionCalls.length === 0)
|
||||
) {
|
||||
throw new Error(
|
||||
"No response received from the server. Please try again.",
|
||||
);
|
||||
}
|
||||
|
||||
// Finalize the message
|
||||
|
|
@ -493,7 +498,10 @@ export function useChatStreaming({
|
|||
if (timeoutId) clearTimeout(timeoutId);
|
||||
|
||||
// If stream was aborted by user, don't handle as error
|
||||
if (streamAbortRef.current?.signal.aborted && !(error as Error).message?.includes("timed out")) {
|
||||
if (
|
||||
streamAbortRef.current?.signal.aborted &&
|
||||
!(error as Error).message?.includes("timed out")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -501,15 +509,21 @@ export function useChatStreaming({
|
|||
setStreamingMessage(null);
|
||||
|
||||
// Create user-friendly error message
|
||||
let errorContent = "Sorry, I couldn't connect to the chat service. Please try again.";
|
||||
let errorContent =
|
||||
"Sorry, I couldn't connect to the chat service. Please try again.";
|
||||
|
||||
const errorMessage = (error as Error).message;
|
||||
if (errorMessage?.includes("timed out")) {
|
||||
errorContent = "The request timed out. The server took too long to respond. Please try again.";
|
||||
errorContent =
|
||||
"The request timed out. The server took too long to respond. Please try again.";
|
||||
} else if (errorMessage?.includes("No response")) {
|
||||
errorContent = "The server didn't return a response. Please try again.";
|
||||
} else if (errorMessage?.includes("NetworkError") || errorMessage?.includes("Failed to fetch")) {
|
||||
errorContent = "Network error. Please check your connection and try again.";
|
||||
} else if (
|
||||
errorMessage?.includes("NetworkError") ||
|
||||
errorMessage?.includes("Failed to fetch")
|
||||
) {
|
||||
errorContent =
|
||||
"Network error. Please check your connection and try again.";
|
||||
} else if (errorMessage?.includes("Server error")) {
|
||||
errorContent = errorMessage; // Use the detailed server error message
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue