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">
|
||||
<DogIcon
|
||||
className="h-6 w-6 transition-colors duration-300"
|
||||
disabled={isCompleted || isInactive}
|
||||
/>
|
||||
{/* 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,20 +100,42 @@ export function AssistantMessage({
|
|||
onToggle={onToggle}
|
||||
/>
|
||||
<div className="relative">
|
||||
<MarkdownRenderer
|
||||
className={cn(
|
||||
"text-sm py-1.5 transition-colors duration-300",
|
||||
isCompleted ? "text-placeholder-foreground" : "text-foreground",
|
||||
)}
|
||||
chatMessage={
|
||||
isStreaming
|
||||
? content.trim()
|
||||
? content +
|
||||
' <span class="inline-block w-1 h-4 bg-primary ml-1 animate-pulse"></span>'
|
||||
: '<span class="text-muted-foreground italic">Thinking<span class="thinking-dots"></span></span>'
|
||||
: content
|
||||
{/* 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",
|
||||
isCompleted ? "text-placeholder-foreground" : "text-foreground",
|
||||
)}
|
||||
chatMessage={
|
||||
isStreaming
|
||||
? content.trim()
|
||||
? content +
|
||||
' <span class="inline-block w-1 h-4 bg-primary ml-1 animate-pulse"></span>'
|
||||
: '<span class="text-muted-foreground italic">Thinking<span class="thinking-dots"></span></span>'
|
||||
: 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,46 +553,35 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
|
|||
)}
|
||||
</button>
|
||||
)}
|
||||
{availableFilters
|
||||
.filter((filter) =>
|
||||
filter.name
|
||||
.toLowerCase()
|
||||
.includes(filterSearchTerm.toLowerCase()),
|
||||
)
|
||||
.map((filter, index) => (
|
||||
<button
|
||||
key={filter.id}
|
||||
type="button"
|
||||
onClick={() => onFilterSelect(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" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="font-medium truncate">
|
||||
{filter.name}
|
||||
</div>
|
||||
{filter.description && (
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{filter.description}
|
||||
</div>
|
||||
)}
|
||||
{filteredFilters.map((filter, index) => (
|
||||
<button
|
||||
key={filter.id}
|
||||
type="button"
|
||||
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" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="font-medium truncate">
|
||||
{filter.name}
|
||||
</div>
|
||||
{selectedFilter?.id === filter.id && (
|
||||
<Check className="h-4 w-4 shrink-0" />
|
||||
{filter.description && (
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{filter.description}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{availableFilters.filter((filter) =>
|
||||
filter.name
|
||||
.toLowerCase()
|
||||
.includes(filterSearchTerm.toLowerCase()),
|
||||
).length === 0 &&
|
||||
filterSearchTerm && (
|
||||
<div className="px-2 py-3 text-sm text-muted-foreground">
|
||||
No filters match "{filterSearchTerm}"
|
||||
</div>
|
||||
)}
|
||||
{selectedFilter?.id === filter.id && (
|
||||
<Check className="h-4 w-4 shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{filteredFilters.length === 0 && filterSearchTerm && (
|
||||
<div className="px-2 py-3 text-sm text-muted-foreground">
|
||||
No filters match "{filterSearchTerm}"
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</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) => ({
|
||||
|
|
@ -124,11 +125,11 @@ function ChatPage() {
|
|||
setMessages((prev) => [...prev, errorMessage]);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
// Show warning if waiting too long (20 seconds)
|
||||
useEffect(() => {
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
|
||||
|
||||
if (isStreamLoading && !streamingMessage) {
|
||||
timeoutId = setTimeout(() => {
|
||||
setWaitingTooLong(true);
|
||||
|
|
@ -136,66 +137,12 @@ function ChatPage() {
|
|||
} else {
|
||||
setWaitingTooLong(false);
|
||||
}
|
||||
|
||||
|
||||
return () => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
};
|
||||
}, [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>
|
||||
),
|
||||
|
|
@ -1331,7 +1099,7 @@ function ChatPage() {
|
|||
isCompleted={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{/* Waiting too long indicator */}
|
||||
{waitingTooLong && !streamingMessage && loading && (
|
||||
<div className="pl-10 space-y-2">
|
||||
|
|
@ -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>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -5,211 +5,211 @@ import { CheckIcon, XIcon } from "lucide-react";
|
|||
import { useEffect, useState } from "react";
|
||||
import AnimatedProcessingIcon from "@/components/icons/animated-processing-icon";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { ONBOARDING_CARD_STEPS_KEY } from "@/lib/constants";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function AnimatedProviderSteps({
|
||||
currentStep,
|
||||
isCompleted,
|
||||
setCurrentStep,
|
||||
steps,
|
||||
storageKey = ONBOARDING_CARD_STEPS_KEY,
|
||||
processingStartTime,
|
||||
hasError = false,
|
||||
currentStep,
|
||||
isCompleted,
|
||||
setCurrentStep,
|
||||
steps,
|
||||
storageKey = ONBOARDING_CARD_STEPS_KEY,
|
||||
processingStartTime,
|
||||
hasError = false,
|
||||
}: {
|
||||
currentStep: number;
|
||||
isCompleted: boolean;
|
||||
setCurrentStep: (step: number) => void;
|
||||
steps: string[];
|
||||
storageKey?: string;
|
||||
processingStartTime?: number | null;
|
||||
hasError?: boolean;
|
||||
currentStep: number;
|
||||
isCompleted: boolean;
|
||||
setCurrentStep: (step: number) => void;
|
||||
steps: string[];
|
||||
storageKey?: string;
|
||||
processingStartTime?: number | null;
|
||||
hasError?: boolean;
|
||||
}) {
|
||||
const [startTime, setStartTime] = useState<number | null>(null);
|
||||
const [elapsedTime, setElapsedTime] = useState<number>(0);
|
||||
const [startTime, setStartTime] = useState<number | null>(null);
|
||||
const [elapsedTime, setElapsedTime] = useState<number>(0);
|
||||
|
||||
// Initialize start time from prop or local storage
|
||||
useEffect(() => {
|
||||
const storedElapsedTime = localStorage.getItem(storageKey);
|
||||
// Initialize start time from prop or local storage
|
||||
useEffect(() => {
|
||||
const storedElapsedTime = localStorage.getItem(storageKey);
|
||||
|
||||
if (isCompleted && storedElapsedTime) {
|
||||
// If completed, use stored elapsed time
|
||||
setElapsedTime(parseFloat(storedElapsedTime));
|
||||
} else if (processingStartTime) {
|
||||
// Use the start time passed from parent (when user clicked Complete)
|
||||
setStartTime(processingStartTime);
|
||||
}
|
||||
}, [storageKey, isCompleted, processingStartTime]);
|
||||
if (isCompleted && storedElapsedTime) {
|
||||
// If completed, use stored elapsed time
|
||||
setElapsedTime(parseFloat(storedElapsedTime));
|
||||
} else if (processingStartTime) {
|
||||
// Use the start time passed from parent (when user clicked Complete)
|
||||
setStartTime(processingStartTime);
|
||||
}
|
||||
}, [storageKey, isCompleted, processingStartTime]);
|
||||
|
||||
// Progress through steps
|
||||
useEffect(() => {
|
||||
if (currentStep < steps.length - 1 && !isCompleted) {
|
||||
const interval = setInterval(() => {
|
||||
setCurrentStep(currentStep + 1);
|
||||
}, 1500);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [currentStep, setCurrentStep, steps, isCompleted]);
|
||||
// Progress through steps
|
||||
useEffect(() => {
|
||||
if (currentStep < steps.length - 1 && !isCompleted) {
|
||||
const interval = setInterval(() => {
|
||||
setCurrentStep(currentStep + 1);
|
||||
}, 1500);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [currentStep, setCurrentStep, steps, isCompleted]);
|
||||
|
||||
// Calculate and store elapsed time when completed
|
||||
useEffect(() => {
|
||||
if (isCompleted && startTime) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
setElapsedTime(elapsed);
|
||||
localStorage.setItem(storageKey, elapsed.toString());
|
||||
}
|
||||
}, [isCompleted, startTime, storageKey]);
|
||||
// Calculate and store elapsed time when completed
|
||||
useEffect(() => {
|
||||
if (isCompleted && startTime) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
setElapsedTime(elapsed);
|
||||
localStorage.setItem(storageKey, elapsed.toString());
|
||||
}
|
||||
}, [isCompleted, startTime, storageKey]);
|
||||
|
||||
const isDone = currentStep >= steps.length && !isCompleted && !hasError;
|
||||
const isDone = currentStep >= steps.length && !isCompleted && !hasError;
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{!isCompleted ? (
|
||||
<motion.div
|
||||
key="processing"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
className="flex flex-col gap-2"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
"transition-all duration-300 relative",
|
||||
isDone || hasError ? "w-3.5 h-3.5" : "w-6 h-6",
|
||||
)}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"text-accent-emerald-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
|
||||
isDone ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<XIcon
|
||||
className={cn(
|
||||
"text-accent-red-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
|
||||
hasError ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<AnimatedProcessingIcon
|
||||
className={cn(
|
||||
"text-current shrink-0 absolute inset-0 transition-all duration-150",
|
||||
isDone || hasError ? "opacity-0" : "opacity-100",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{!isCompleted ? (
|
||||
<motion.div
|
||||
key="processing"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
className="flex flex-col gap-2"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
"transition-all duration-300 relative",
|
||||
isDone || hasError ? "w-3.5 h-3.5" : "w-6 h-6",
|
||||
)}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"text-accent-emerald-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
|
||||
isDone ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<XIcon
|
||||
className={cn(
|
||||
"text-accent-red-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
|
||||
hasError ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<AnimatedProcessingIcon
|
||||
className={cn(
|
||||
"text-current shrink-0 absolute inset-0 transition-all duration-150",
|
||||
isDone || hasError ? "opacity-0" : "opacity-100",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className="!text-mmd font-medium text-muted-foreground">
|
||||
{hasError ? "Error" : isDone ? "Done" : "Thinking"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden">
|
||||
<AnimatePresence>
|
||||
{!isDone && !hasError && (
|
||||
<motion.div
|
||||
initial={{ opacity: 1, y: 0, height: "auto" }}
|
||||
exit={{ opacity: 0, y: -24, height: 0 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
className="flex items-center gap-4 overflow-y-hidden relative h-6"
|
||||
>
|
||||
<div className="w-px h-6 bg-border ml-3" />
|
||||
<div className="relative h-5 w-full">
|
||||
<AnimatePresence mode="sync" initial={false}>
|
||||
<motion.span
|
||||
key={currentStep}
|
||||
initial={{ y: 24, opacity: 0 }}
|
||||
animate={{ y: 0, opacity: 1 }}
|
||||
exit={{ y: -24, opacity: 0 }}
|
||||
transition={{ duration: 0.3, ease: "easeInOut" }}
|
||||
className="text-mmd font-medium text-primary absolute left-0"
|
||||
>
|
||||
{steps[currentStep]}
|
||||
</motion.span>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="completed"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="steps" className="border-none">
|
||||
<AccordionTrigger className="hover:no-underline p-0 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-mmd font-medium text-muted-foreground">
|
||||
{`Initialized in ${(elapsedTime / 1000).toFixed(1)} seconds`}
|
||||
</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pl-0 pt-2 pb-0">
|
||||
<div className="relative pl-1">
|
||||
{/* Connecting line on the left */}
|
||||
<motion.div
|
||||
className="absolute left-[7px] top-0 bottom-0 w-px bg-border z-0"
|
||||
initial={{ scaleY: 0 }}
|
||||
animate={{ scaleY: 1 }}
|
||||
transition={{ duration: 0.3, ease: "easeOut" }}
|
||||
style={{ transformOrigin: "top" }}
|
||||
/>
|
||||
<span className="!text-mmd font-medium text-muted-foreground">
|
||||
{hasError ? "Error" : isDone ? "Done" : "Thinking"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden">
|
||||
<AnimatePresence>
|
||||
{!isDone && !hasError && (
|
||||
<motion.div
|
||||
initial={{ opacity: 1, y: 0, height: "auto" }}
|
||||
exit={{ opacity: 0, y: -24, height: 0 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
className="flex items-center gap-4 overflow-y-hidden relative h-6"
|
||||
>
|
||||
<div className="w-px h-6 bg-border ml-3" />
|
||||
<div className="relative h-5 w-full">
|
||||
<AnimatePresence mode="sync" initial={false}>
|
||||
<motion.span
|
||||
key={currentStep}
|
||||
initial={{ y: 24, opacity: 0 }}
|
||||
animate={{ y: 0, opacity: 1 }}
|
||||
exit={{ y: -24, opacity: 0 }}
|
||||
transition={{ duration: 0.3, ease: "easeInOut" }}
|
||||
className="text-mmd font-medium text-primary absolute left-0"
|
||||
>
|
||||
{steps[currentStep]}
|
||||
</motion.span>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="completed"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="steps" className="border-none">
|
||||
<AccordionTrigger className="hover:no-underline p-0 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-mmd font-medium text-muted-foreground">
|
||||
{`Initialized in ${(elapsedTime / 1000).toFixed(1)} seconds`}
|
||||
</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pl-0 pt-2 pb-0">
|
||||
<div className="relative pl-1">
|
||||
{/* Connecting line on the left */}
|
||||
<motion.div
|
||||
className="absolute left-[7px] top-0 bottom-0 w-px bg-border z-0"
|
||||
initial={{ scaleY: 0 }}
|
||||
animate={{ scaleY: 1 }}
|
||||
transition={{ duration: 0.3, ease: "easeOut" }}
|
||||
style={{ transformOrigin: "top" }}
|
||||
/>
|
||||
|
||||
<div className="space-y-3 ml-4">
|
||||
<AnimatePresence>
|
||||
{steps.map((step, index) => (
|
||||
<motion.div
|
||||
key={step}
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{
|
||||
duration: 0.3,
|
||||
delay: index * 0.05,
|
||||
}}
|
||||
className="flex items-center gap-1.5"
|
||||
>
|
||||
<motion.div
|
||||
className="relative w-3.5 h-3.5 shrink-0 z-10 bg-background"
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
delay: index * 0.05 + 0.1,
|
||||
}}
|
||||
>
|
||||
<motion.div
|
||||
key="check"
|
||||
initial={{ scale: 0, rotate: -180 }}
|
||||
animate={{ scale: 1, rotate: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<CheckIcon className="text-accent-emerald-foreground w-3.5 h-3.5" />
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
<span className="text-mmd text-muted-foreground">
|
||||
{step}
|
||||
</span>
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
<div className="space-y-3 ml-4">
|
||||
<AnimatePresence>
|
||||
{steps.map((step, index) => (
|
||||
<motion.div
|
||||
key={step}
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{
|
||||
duration: 0.3,
|
||||
delay: index * 0.05,
|
||||
}}
|
||||
className="flex items-center gap-1.5"
|
||||
>
|
||||
<motion.div
|
||||
className="relative w-3.5 h-3.5 shrink-0 z-10 bg-background"
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
delay: index * 0.05 + 0.1,
|
||||
}}
|
||||
>
|
||||
<motion.div
|
||||
key="check"
|
||||
initial={{ scale: 0, rotate: -180 }}
|
||||
animate={{ scale: 1, rotate: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<CheckIcon className="text-accent-emerald-foreground w-3.5 h-3.5" />
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
<span className="text-mmd text-muted-foreground">
|
||||
{step}
|
||||
</span>
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import { Info, X } from "lucide-react";
|
|||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
type OnboardingVariables,
|
||||
useOnboardingMutation,
|
||||
type OnboardingVariables,
|
||||
useOnboardingMutation,
|
||||
} from "@/app/api/mutations/useOnboardingMutation";
|
||||
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
|
||||
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
|
||||
|
|
@ -20,9 +20,9 @@ import OpenAILogo from "@/components/icons/openai-logo";
|
|||
import { Button } from "@/components/ui/button";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { ONBOARDING_CARD_STEPS_KEY } from "@/lib/constants";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
|
@ -34,507 +34,507 @@ import { OpenAIOnboarding } from "./openai-onboarding";
|
|||
import { TabTrigger } from "./tab-trigger";
|
||||
|
||||
interface OnboardingCardProps {
|
||||
onComplete: () => void;
|
||||
isCompleted?: boolean;
|
||||
isEmbedding?: boolean;
|
||||
setIsLoadingModels?: (isLoading: boolean) => void;
|
||||
setLoadingStatus?: (status: string[]) => void;
|
||||
onComplete: () => void;
|
||||
isCompleted?: boolean;
|
||||
isEmbedding?: boolean;
|
||||
setIsLoadingModels?: (isLoading: boolean) => void;
|
||||
setLoadingStatus?: (status: string[]) => void;
|
||||
}
|
||||
|
||||
const STEP_LIST = [
|
||||
"Setting up your model provider",
|
||||
"Defining schema",
|
||||
"Configuring Langflow",
|
||||
"Setting up your model provider",
|
||||
"Defining schema",
|
||||
"Configuring Langflow",
|
||||
];
|
||||
|
||||
const EMBEDDING_STEP_LIST = [
|
||||
"Setting up your model provider",
|
||||
"Defining schema",
|
||||
"Configuring Langflow",
|
||||
"Ingesting sample data",
|
||||
"Setting up your model provider",
|
||||
"Defining schema",
|
||||
"Configuring Langflow",
|
||||
"Ingesting sample data",
|
||||
];
|
||||
|
||||
const OnboardingCard = ({
|
||||
onComplete,
|
||||
isEmbedding = false,
|
||||
isCompleted = false,
|
||||
onComplete,
|
||||
isEmbedding = false,
|
||||
isCompleted = false,
|
||||
}: OnboardingCardProps) => {
|
||||
const { isHealthy: isDoclingHealthy } = useDoclingHealth();
|
||||
const { isHealthy: isDoclingHealthy } = useDoclingHealth();
|
||||
|
||||
const [modelProvider, setModelProvider] = useState<string>(
|
||||
isEmbedding ? "openai" : "anthropic",
|
||||
);
|
||||
const [modelProvider, setModelProvider] = useState<string>(
|
||||
isEmbedding ? "openai" : "anthropic",
|
||||
);
|
||||
|
||||
const [sampleDataset, setSampleDataset] = useState<boolean>(true);
|
||||
const [sampleDataset, setSampleDataset] = useState<boolean>(true);
|
||||
|
||||
const [isLoadingModels, setIsLoadingModels] = useState<boolean>(false);
|
||||
const [isLoadingModels, setIsLoadingModels] = useState<boolean>(false);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Fetch current settings to check if providers are already configured
|
||||
const { data: currentSettings } = useGetSettingsQuery();
|
||||
// Fetch current settings to check if providers are already configured
|
||||
const { data: currentSettings } = useGetSettingsQuery();
|
||||
|
||||
const handleSetModelProvider = (provider: string) => {
|
||||
setIsLoadingModels(false);
|
||||
setModelProvider(provider);
|
||||
setSettings({
|
||||
[isEmbedding ? "embedding_provider" : "llm_provider"]: provider,
|
||||
embedding_model: "",
|
||||
llm_model: "",
|
||||
});
|
||||
setError(null);
|
||||
};
|
||||
const handleSetModelProvider = (provider: string) => {
|
||||
setIsLoadingModels(false);
|
||||
setModelProvider(provider);
|
||||
setSettings({
|
||||
[isEmbedding ? "embedding_provider" : "llm_provider"]: provider,
|
||||
embedding_model: "",
|
||||
llm_model: "",
|
||||
});
|
||||
setError(null);
|
||||
};
|
||||
|
||||
// Check if the selected provider is already configured
|
||||
const isProviderAlreadyConfigured = (provider: string): boolean => {
|
||||
if (!isEmbedding || !currentSettings?.providers) return false;
|
||||
// Check if the selected provider is already configured
|
||||
const isProviderAlreadyConfigured = (provider: string): boolean => {
|
||||
if (!isEmbedding || !currentSettings?.providers) return false;
|
||||
|
||||
// Check if provider has been explicitly configured (not just from env vars)
|
||||
if (provider === "openai") {
|
||||
return currentSettings.providers.openai?.configured === true;
|
||||
} else if (provider === "anthropic") {
|
||||
return currentSettings.providers.anthropic?.configured === true;
|
||||
} else if (provider === "watsonx") {
|
||||
return currentSettings.providers.watsonx?.configured === true;
|
||||
} else if (provider === "ollama") {
|
||||
return currentSettings.providers.ollama?.configured === true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
// Check if provider has been explicitly configured (not just from env vars)
|
||||
if (provider === "openai") {
|
||||
return currentSettings.providers.openai?.configured === true;
|
||||
} else if (provider === "anthropic") {
|
||||
return currentSettings.providers.anthropic?.configured === true;
|
||||
} else if (provider === "watsonx") {
|
||||
return currentSettings.providers.watsonx?.configured === true;
|
||||
} else if (provider === "ollama") {
|
||||
return currentSettings.providers.ollama?.configured === true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const showProviderConfiguredMessage =
|
||||
isProviderAlreadyConfigured(modelProvider);
|
||||
const providerAlreadyConfigured =
|
||||
isEmbedding && showProviderConfiguredMessage;
|
||||
const showProviderConfiguredMessage =
|
||||
isProviderAlreadyConfigured(modelProvider);
|
||||
const providerAlreadyConfigured =
|
||||
isEmbedding && showProviderConfiguredMessage;
|
||||
|
||||
const totalSteps = isEmbedding
|
||||
? EMBEDDING_STEP_LIST.length
|
||||
: STEP_LIST.length;
|
||||
const totalSteps = isEmbedding
|
||||
? EMBEDDING_STEP_LIST.length
|
||||
: STEP_LIST.length;
|
||||
|
||||
const [settings, setSettings] = useState<OnboardingVariables>({
|
||||
[isEmbedding ? "embedding_provider" : "llm_provider"]: modelProvider,
|
||||
embedding_model: "",
|
||||
llm_model: "",
|
||||
// Provider-specific fields will be set by provider components
|
||||
openai_api_key: "",
|
||||
anthropic_api_key: "",
|
||||
watsonx_api_key: "",
|
||||
watsonx_endpoint: "",
|
||||
watsonx_project_id: "",
|
||||
ollama_endpoint: "",
|
||||
});
|
||||
const [settings, setSettings] = useState<OnboardingVariables>({
|
||||
[isEmbedding ? "embedding_provider" : "llm_provider"]: modelProvider,
|
||||
embedding_model: "",
|
||||
llm_model: "",
|
||||
// Provider-specific fields will be set by provider components
|
||||
openai_api_key: "",
|
||||
anthropic_api_key: "",
|
||||
watsonx_api_key: "",
|
||||
watsonx_endpoint: "",
|
||||
watsonx_project_id: "",
|
||||
ollama_endpoint: "",
|
||||
});
|
||||
|
||||
const [currentStep, setCurrentStep] = useState<number | null>(
|
||||
isCompleted ? totalSteps : null,
|
||||
);
|
||||
const [currentStep, setCurrentStep] = useState<number | null>(
|
||||
isCompleted ? totalSteps : null,
|
||||
);
|
||||
|
||||
const [processingStartTime, setProcessingStartTime] = useState<number | null>(
|
||||
null,
|
||||
);
|
||||
const [processingStartTime, setProcessingStartTime] = useState<number | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Query tasks to track completion
|
||||
const { data: tasks } = useGetTasksQuery({
|
||||
enabled: currentStep !== null, // Only poll when onboarding has started
|
||||
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during onboarding
|
||||
});
|
||||
// Query tasks to track completion
|
||||
const { data: tasks } = useGetTasksQuery({
|
||||
enabled: currentStep !== null, // Only poll when onboarding has started
|
||||
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during onboarding
|
||||
});
|
||||
|
||||
// Monitor tasks and call onComplete when all tasks are done
|
||||
useEffect(() => {
|
||||
if (currentStep === null || !tasks || !isEmbedding) {
|
||||
return;
|
||||
}
|
||||
// Monitor tasks and call onComplete when all tasks are done
|
||||
useEffect(() => {
|
||||
if (currentStep === null || !tasks || !isEmbedding) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if there are any active tasks (pending, running, or processing)
|
||||
const activeTasks = tasks.find(
|
||||
(task) =>
|
||||
task.status === "pending" ||
|
||||
task.status === "running" ||
|
||||
task.status === "processing",
|
||||
);
|
||||
// Check if there are any active tasks (pending, running, or processing)
|
||||
const activeTasks = tasks.find(
|
||||
(task) =>
|
||||
task.status === "pending" ||
|
||||
task.status === "running" ||
|
||||
task.status === "processing",
|
||||
);
|
||||
|
||||
// If no active tasks and we've started onboarding, complete it
|
||||
if (
|
||||
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
|
||||
tasks.length > 0 &&
|
||||
!isCompleted
|
||||
) {
|
||||
// Set to final step to show "Done"
|
||||
setCurrentStep(totalSteps);
|
||||
// Wait a bit before completing
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
}
|
||||
}, [tasks, currentStep, onComplete, isCompleted, isEmbedding, totalSteps]);
|
||||
// If no active tasks and we've started onboarding, complete it
|
||||
if (
|
||||
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
|
||||
tasks.length > 0 &&
|
||||
!isCompleted
|
||||
) {
|
||||
// Set to final step to show "Done"
|
||||
setCurrentStep(totalSteps);
|
||||
// Wait a bit before completing
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
}
|
||||
}, [tasks, currentStep, onComplete, isCompleted, isEmbedding, totalSteps]);
|
||||
|
||||
// Mutations
|
||||
const onboardingMutation = useOnboardingMutation({
|
||||
onSuccess: (data) => {
|
||||
console.log("Onboarding completed successfully", data);
|
||||
// Update provider health cache to healthy since backend just validated
|
||||
const provider =
|
||||
(isEmbedding ? settings.embedding_provider : settings.llm_provider) ||
|
||||
modelProvider;
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: provider,
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
setError(null);
|
||||
if (!isEmbedding) {
|
||||
setCurrentStep(totalSteps);
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
} else {
|
||||
setCurrentStep(0);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
setError(error.message);
|
||||
setCurrentStep(totalSteps);
|
||||
// Reset to provider selection after 1 second
|
||||
setTimeout(() => {
|
||||
setCurrentStep(null);
|
||||
}, 1000);
|
||||
},
|
||||
});
|
||||
// Mutations
|
||||
const onboardingMutation = useOnboardingMutation({
|
||||
onSuccess: (data) => {
|
||||
console.log("Onboarding completed successfully", data);
|
||||
// Update provider health cache to healthy since backend just validated
|
||||
const provider =
|
||||
(isEmbedding ? settings.embedding_provider : settings.llm_provider) ||
|
||||
modelProvider;
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: provider,
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
setError(null);
|
||||
if (!isEmbedding) {
|
||||
setCurrentStep(totalSteps);
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
} else {
|
||||
setCurrentStep(0);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
setError(error.message);
|
||||
setCurrentStep(totalSteps);
|
||||
// Reset to provider selection after 1 second
|
||||
setTimeout(() => {
|
||||
setCurrentStep(null);
|
||||
}, 1000);
|
||||
},
|
||||
});
|
||||
|
||||
const handleComplete = () => {
|
||||
const currentProvider = isEmbedding
|
||||
? settings.embedding_provider
|
||||
: settings.llm_provider;
|
||||
const handleComplete = () => {
|
||||
const currentProvider = isEmbedding
|
||||
? settings.embedding_provider
|
||||
: settings.llm_provider;
|
||||
|
||||
if (
|
||||
!currentProvider ||
|
||||
(isEmbedding &&
|
||||
!settings.embedding_model &&
|
||||
!showProviderConfiguredMessage) ||
|
||||
(!isEmbedding && !settings.llm_model)
|
||||
) {
|
||||
toast.error("Please complete all required fields");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!currentProvider ||
|
||||
(isEmbedding &&
|
||||
!settings.embedding_model &&
|
||||
!showProviderConfiguredMessage) ||
|
||||
(!isEmbedding && !settings.llm_model)
|
||||
) {
|
||||
toast.error("Please complete all required fields");
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear any previous error
|
||||
setError(null);
|
||||
// Clear any previous error
|
||||
setError(null);
|
||||
|
||||
// Prepare onboarding data with provider-specific fields
|
||||
const onboardingData: OnboardingVariables = {
|
||||
sample_data: sampleDataset,
|
||||
};
|
||||
// Prepare onboarding data with provider-specific fields
|
||||
const onboardingData: OnboardingVariables = {
|
||||
sample_data: sampleDataset,
|
||||
};
|
||||
|
||||
// Set the provider field
|
||||
if (isEmbedding) {
|
||||
onboardingData.embedding_provider = currentProvider;
|
||||
// If provider is already configured, use the existing embedding model from settings
|
||||
// Otherwise, use the embedding model from the form
|
||||
if (
|
||||
showProviderConfiguredMessage &&
|
||||
currentSettings?.knowledge?.embedding_model
|
||||
) {
|
||||
onboardingData.embedding_model =
|
||||
currentSettings.knowledge.embedding_model;
|
||||
} else {
|
||||
onboardingData.embedding_model = settings.embedding_model;
|
||||
}
|
||||
} else {
|
||||
onboardingData.llm_provider = currentProvider;
|
||||
onboardingData.llm_model = settings.llm_model;
|
||||
}
|
||||
// Set the provider field
|
||||
if (isEmbedding) {
|
||||
onboardingData.embedding_provider = currentProvider;
|
||||
// If provider is already configured, use the existing embedding model from settings
|
||||
// Otherwise, use the embedding model from the form
|
||||
if (
|
||||
showProviderConfiguredMessage &&
|
||||
currentSettings?.knowledge?.embedding_model
|
||||
) {
|
||||
onboardingData.embedding_model =
|
||||
currentSettings.knowledge.embedding_model;
|
||||
} else {
|
||||
onboardingData.embedding_model = settings.embedding_model;
|
||||
}
|
||||
} else {
|
||||
onboardingData.llm_provider = currentProvider;
|
||||
onboardingData.llm_model = settings.llm_model;
|
||||
}
|
||||
|
||||
// Add provider-specific credentials based on the selected provider
|
||||
if (currentProvider === "openai" && settings.openai_api_key) {
|
||||
onboardingData.openai_api_key = settings.openai_api_key;
|
||||
} else if (currentProvider === "anthropic" && settings.anthropic_api_key) {
|
||||
onboardingData.anthropic_api_key = settings.anthropic_api_key;
|
||||
} else if (currentProvider === "watsonx") {
|
||||
if (settings.watsonx_api_key) {
|
||||
onboardingData.watsonx_api_key = settings.watsonx_api_key;
|
||||
}
|
||||
if (settings.watsonx_endpoint) {
|
||||
onboardingData.watsonx_endpoint = settings.watsonx_endpoint;
|
||||
}
|
||||
if (settings.watsonx_project_id) {
|
||||
onboardingData.watsonx_project_id = settings.watsonx_project_id;
|
||||
}
|
||||
} else if (currentProvider === "ollama" && settings.ollama_endpoint) {
|
||||
onboardingData.ollama_endpoint = settings.ollama_endpoint;
|
||||
}
|
||||
// Add provider-specific credentials based on the selected provider
|
||||
if (currentProvider === "openai" && settings.openai_api_key) {
|
||||
onboardingData.openai_api_key = settings.openai_api_key;
|
||||
} else if (currentProvider === "anthropic" && settings.anthropic_api_key) {
|
||||
onboardingData.anthropic_api_key = settings.anthropic_api_key;
|
||||
} else if (currentProvider === "watsonx") {
|
||||
if (settings.watsonx_api_key) {
|
||||
onboardingData.watsonx_api_key = settings.watsonx_api_key;
|
||||
}
|
||||
if (settings.watsonx_endpoint) {
|
||||
onboardingData.watsonx_endpoint = settings.watsonx_endpoint;
|
||||
}
|
||||
if (settings.watsonx_project_id) {
|
||||
onboardingData.watsonx_project_id = settings.watsonx_project_id;
|
||||
}
|
||||
} else if (currentProvider === "ollama" && settings.ollama_endpoint) {
|
||||
onboardingData.ollama_endpoint = settings.ollama_endpoint;
|
||||
}
|
||||
|
||||
// Record the start time when user clicks Complete
|
||||
setProcessingStartTime(Date.now());
|
||||
onboardingMutation.mutate(onboardingData);
|
||||
setCurrentStep(0);
|
||||
};
|
||||
// Record the start time when user clicks Complete
|
||||
setProcessingStartTime(Date.now());
|
||||
onboardingMutation.mutate(onboardingData);
|
||||
setCurrentStep(0);
|
||||
};
|
||||
|
||||
const isComplete =
|
||||
(isEmbedding &&
|
||||
(!!settings.embedding_model || showProviderConfiguredMessage)) ||
|
||||
(!isEmbedding && !!settings.llm_model && isDoclingHealthy);
|
||||
const isComplete =
|
||||
(isEmbedding &&
|
||||
(!!settings.embedding_model || showProviderConfiguredMessage)) ||
|
||||
(!isEmbedding && !!settings.llm_model && isDoclingHealthy);
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{currentStep === null ? (
|
||||
<motion.div
|
||||
key="onboarding-form"
|
||||
initial={{ opacity: 0, y: -24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<div className={`w-full max-w-[600px] flex flex-col`}>
|
||||
<AnimatePresence mode="wait">
|
||||
{error && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 1, y: 0, height: "auto" }}
|
||||
exit={{ opacity: 0, y: -10, height: 0 }}
|
||||
>
|
||||
<div className="pb-6 flex items-center gap-4">
|
||||
<X className="w-4 h-4 text-destructive shrink-0" />
|
||||
<span className="text-mmd text-muted-foreground">
|
||||
{error}
|
||||
</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className={`w-full flex flex-col gap-6`}>
|
||||
<Tabs
|
||||
defaultValue={modelProvider}
|
||||
onValueChange={handleSetModelProvider}
|
||||
>
|
||||
<TabsList className="mb-4">
|
||||
{!isEmbedding && (
|
||||
<TabsTrigger
|
||||
value="anthropic"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "anthropic" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "anthropic"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "anthropic"
|
||||
? "bg-[#D97757]"
|
||||
: "bg-muted",
|
||||
)}
|
||||
>
|
||||
<AnthropicLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "anthropic"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
Anthropic
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger
|
||||
value="openai"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "openai" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "openai"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "openai" ? "bg-white" : "bg-muted",
|
||||
)}
|
||||
>
|
||||
<OpenAILogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "openai"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
OpenAI
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="watsonx"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "watsonx" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "watsonx"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "watsonx"
|
||||
? "bg-[#1063FE]"
|
||||
: "bg-muted",
|
||||
)}
|
||||
>
|
||||
<IBMLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "watsonx"
|
||||
? "text-white"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
IBM watsonx.ai
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="ollama"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "ollama" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "ollama"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "ollama" ? "bg-white" : "bg-muted",
|
||||
)}
|
||||
>
|
||||
<OllamaLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "ollama"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
Ollama
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
{!isEmbedding && (
|
||||
<TabsContent value="anthropic">
|
||||
<AnthropicOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
hasEnvApiKey={
|
||||
currentSettings?.providers?.anthropic?.has_api_key ===
|
||||
true
|
||||
}
|
||||
/>
|
||||
</TabsContent>
|
||||
)}
|
||||
<TabsContent value="openai">
|
||||
<OpenAIOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
hasEnvApiKey={
|
||||
currentSettings?.providers?.openai?.has_api_key === true
|
||||
}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="watsonx">
|
||||
<IBMOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="ollama">
|
||||
<OllamaOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{currentStep === null ? (
|
||||
<motion.div
|
||||
key="onboarding-form"
|
||||
initial={{ opacity: 0, y: -24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<div className={`w-full max-w-[600px] flex flex-col`}>
|
||||
<AnimatePresence mode="wait">
|
||||
{error && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 1, y: 0, height: "auto" }}
|
||||
exit={{ opacity: 0, y: -10, height: 0 }}
|
||||
>
|
||||
<div className="pb-6 flex items-center gap-4">
|
||||
<X className="w-4 h-4 text-destructive shrink-0" />
|
||||
<span className="text-mmd text-muted-foreground">
|
||||
{error}
|
||||
</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className={`w-full flex flex-col gap-6`}>
|
||||
<Tabs
|
||||
defaultValue={modelProvider}
|
||||
onValueChange={handleSetModelProvider}
|
||||
>
|
||||
<TabsList className="mb-4">
|
||||
{!isEmbedding && (
|
||||
<TabsTrigger
|
||||
value="anthropic"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "anthropic" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "anthropic"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "anthropic"
|
||||
? "bg-[#D97757]"
|
||||
: "bg-muted",
|
||||
)}
|
||||
>
|
||||
<AnthropicLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "anthropic"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
Anthropic
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger
|
||||
value="openai"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "openai" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "openai"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "openai" ? "bg-white" : "bg-muted",
|
||||
)}
|
||||
>
|
||||
<OpenAILogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "openai"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
OpenAI
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="watsonx"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "watsonx" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "watsonx"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "watsonx"
|
||||
? "bg-[#1063FE]"
|
||||
: "bg-muted",
|
||||
)}
|
||||
>
|
||||
<IBMLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "watsonx"
|
||||
? "text-white"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
IBM watsonx.ai
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="ollama"
|
||||
className={cn(
|
||||
error &&
|
||||
modelProvider === "ollama" &&
|
||||
"data-[state=active]:border-destructive",
|
||||
)}
|
||||
>
|
||||
<TabTrigger
|
||||
selected={modelProvider === "ollama"}
|
||||
isLoading={isLoadingModels}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
|
||||
modelProvider === "ollama" ? "bg-white" : "bg-muted",
|
||||
)}
|
||||
>
|
||||
<OllamaLogo
|
||||
className={cn(
|
||||
"w-4 h-4 shrink-0",
|
||||
modelProvider === "ollama"
|
||||
? "text-black"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
Ollama
|
||||
</TabTrigger>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
{!isEmbedding && (
|
||||
<TabsContent value="anthropic">
|
||||
<AnthropicOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
hasEnvApiKey={
|
||||
currentSettings?.providers?.anthropic?.has_api_key ===
|
||||
true
|
||||
}
|
||||
/>
|
||||
</TabsContent>
|
||||
)}
|
||||
<TabsContent value="openai">
|
||||
<OpenAIOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
hasEnvApiKey={
|
||||
currentSettings?.providers?.openai?.has_api_key === true
|
||||
}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="watsonx">
|
||||
<IBMOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="ollama">
|
||||
<OllamaOnboarding
|
||||
setSettings={setSettings}
|
||||
sampleDataset={sampleDataset}
|
||||
setSampleDataset={setSampleDataset}
|
||||
setIsLoadingModels={setIsLoadingModels}
|
||||
isEmbedding={isEmbedding}
|
||||
alreadyConfigured={providerAlreadyConfigured}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleComplete}
|
||||
disabled={!isComplete || isLoadingModels}
|
||||
loading={onboardingMutation.isPending}
|
||||
>
|
||||
<span className="select-none">Complete</span>
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
{!isComplete && (
|
||||
<TooltipContent>
|
||||
{isLoadingModels
|
||||
? "Loading models..."
|
||||
: !!settings.llm_model &&
|
||||
!!settings.embedding_model &&
|
||||
!isDoclingHealthy
|
||||
? "docling-serve must be running to continue"
|
||||
: "Please fill in all required fields"}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="provider-steps"
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<AnimatedProviderSteps
|
||||
currentStep={currentStep}
|
||||
isCompleted={isCompleted}
|
||||
setCurrentStep={setCurrentStep}
|
||||
steps={isEmbedding ? EMBEDDING_STEP_LIST : STEP_LIST}
|
||||
processingStartTime={processingStartTime}
|
||||
storageKey={ONBOARDING_CARD_STEPS_KEY}
|
||||
hasError={!!error}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleComplete}
|
||||
disabled={!isComplete || isLoadingModels}
|
||||
loading={onboardingMutation.isPending}
|
||||
>
|
||||
<span className="select-none">Complete</span>
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
{!isComplete && (
|
||||
<TooltipContent>
|
||||
{isLoadingModels
|
||||
? "Loading models..."
|
||||
: !!settings.llm_model &&
|
||||
!!settings.embedding_model &&
|
||||
!isDoclingHealthy
|
||||
? "docling-serve must be running to continue"
|
||||
: "Please fill in all required fields"}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="provider-steps"
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<AnimatedProviderSteps
|
||||
currentStep={currentStep}
|
||||
isCompleted={isCompleted}
|
||||
setCurrentStep={setCurrentStep}
|
||||
steps={isEmbedding ? EMBEDDING_STEP_LIST : STEP_LIST}
|
||||
processingStartTime={processingStartTime}
|
||||
storageKey={ONBOARDING_CARD_STEPS_KEY}
|
||||
hasError={!!error}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
};
|
||||
|
||||
export default OnboardingCard;
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -8,152 +8,152 @@ import { ONBOARDING_UPLOAD_STEPS_KEY } from "@/lib/constants";
|
|||
import { uploadFile } from "@/lib/upload-utils";
|
||||
|
||||
interface OnboardingUploadProps {
|
||||
onComplete: () => void;
|
||||
onComplete: () => void;
|
||||
}
|
||||
|
||||
const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [currentStep, setCurrentStep] = useState<number | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [currentStep, setCurrentStep] = useState<number | null>(null);
|
||||
|
||||
const STEP_LIST = [
|
||||
"Uploading your document",
|
||||
"Generating embeddings",
|
||||
"Ingesting document",
|
||||
"Processing your document",
|
||||
];
|
||||
const STEP_LIST = [
|
||||
"Uploading your document",
|
||||
"Generating embeddings",
|
||||
"Ingesting document",
|
||||
"Processing your document",
|
||||
];
|
||||
|
||||
// Query tasks to track completion
|
||||
const { data: tasks } = useGetTasksQuery({
|
||||
enabled: currentStep !== null, // Only poll when upload has started
|
||||
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during upload
|
||||
});
|
||||
// Query tasks to track completion
|
||||
const { data: tasks } = useGetTasksQuery({
|
||||
enabled: currentStep !== null, // Only poll when upload has started
|
||||
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during upload
|
||||
});
|
||||
|
||||
const { refetch: refetchNudges } = useGetNudgesQuery(null);
|
||||
const { refetch: refetchNudges } = useGetNudgesQuery(null);
|
||||
|
||||
// Monitor tasks and call onComplete when file processing is done
|
||||
useEffect(() => {
|
||||
if (currentStep === null || !tasks) {
|
||||
return;
|
||||
}
|
||||
// Monitor tasks and call onComplete when file processing is done
|
||||
useEffect(() => {
|
||||
if (currentStep === null || !tasks) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if there are any active tasks (pending, running, or processing)
|
||||
const activeTasks = tasks.find(
|
||||
(task) =>
|
||||
task.status === "pending" ||
|
||||
task.status === "running" ||
|
||||
task.status === "processing",
|
||||
);
|
||||
// Check if there are any active tasks (pending, running, or processing)
|
||||
const activeTasks = tasks.find(
|
||||
(task) =>
|
||||
task.status === "pending" ||
|
||||
task.status === "running" ||
|
||||
task.status === "processing",
|
||||
);
|
||||
|
||||
// If no active tasks and we have more than 1 task (initial + new upload), complete it
|
||||
if (
|
||||
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
|
||||
tasks.length > 1
|
||||
) {
|
||||
// Set to final step to show "Done"
|
||||
setCurrentStep(STEP_LIST.length);
|
||||
// If no active tasks and we have more than 1 task (initial + new upload), complete it
|
||||
if (
|
||||
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
|
||||
tasks.length > 1
|
||||
) {
|
||||
// Set to final step to show "Done"
|
||||
setCurrentStep(STEP_LIST.length);
|
||||
|
||||
// Refetch nudges to get new ones
|
||||
refetchNudges();
|
||||
// Refetch nudges to get new ones
|
||||
refetchNudges();
|
||||
|
||||
// Wait a bit before completing
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
}
|
||||
}, [tasks, currentStep, onComplete, refetchNudges]);
|
||||
// Wait a bit before completing
|
||||
setTimeout(() => {
|
||||
onComplete();
|
||||
}, 1000);
|
||||
}
|
||||
}, [tasks, currentStep, onComplete, refetchNudges]);
|
||||
|
||||
const resetFileInput = () => {
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
const resetFileInput = () => {
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const handleUploadClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
const handleUploadClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const performUpload = async (file: File) => {
|
||||
setIsUploading(true);
|
||||
try {
|
||||
setCurrentStep(0);
|
||||
await uploadFile(file, true);
|
||||
console.log("Document upload task started successfully");
|
||||
// Move to processing step - task monitoring will handle completion
|
||||
setTimeout(() => {
|
||||
setCurrentStep(1);
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error("Upload failed", (error as Error).message);
|
||||
// Reset on error
|
||||
setCurrentStep(null);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
const performUpload = async (file: File) => {
|
||||
setIsUploading(true);
|
||||
try {
|
||||
setCurrentStep(0);
|
||||
await uploadFile(file, true);
|
||||
console.log("Document upload task started successfully");
|
||||
// Move to processing step - task monitoring will handle completion
|
||||
setTimeout(() => {
|
||||
setCurrentStep(1);
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error("Upload failed", (error as Error).message);
|
||||
// Reset on error
|
||||
setCurrentStep(null);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFile = event.target.files?.[0];
|
||||
if (!selectedFile) {
|
||||
resetFileInput();
|
||||
return;
|
||||
}
|
||||
const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFile = event.target.files?.[0];
|
||||
if (!selectedFile) {
|
||||
resetFileInput();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await performUpload(selectedFile);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Unable to prepare file for upload",
|
||||
(error as Error).message,
|
||||
);
|
||||
} finally {
|
||||
resetFileInput();
|
||||
}
|
||||
};
|
||||
try {
|
||||
await performUpload(selectedFile);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Unable to prepare file for upload",
|
||||
(error as Error).message,
|
||||
);
|
||||
} finally {
|
||||
resetFileInput();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{currentStep === null ? (
|
||||
<motion.div
|
||||
key="user-ingest"
|
||||
initial={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleUploadClick}
|
||||
disabled={isUploading}
|
||||
>
|
||||
<div>{isUploading ? "Uploading..." : "Add a document"}</div>
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
|
||||
/>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="ingest-steps"
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<AnimatedProviderSteps
|
||||
currentStep={currentStep}
|
||||
setCurrentStep={setCurrentStep}
|
||||
isCompleted={false}
|
||||
steps={STEP_LIST}
|
||||
storageKey={ONBOARDING_UPLOAD_STEPS_KEY}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
{currentStep === null ? (
|
||||
<motion.div
|
||||
key="user-ingest"
|
||||
initial={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -24 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleUploadClick}
|
||||
disabled={isUploading}
|
||||
>
|
||||
<div>{isUploading ? "Uploading..." : "Add a document"}</div>
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
|
||||
/>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="ingest-steps"
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||
>
|
||||
<AnimatedProviderSteps
|
||||
currentStep={currentStep}
|
||||
setCurrentStep={setCurrentStep}
|
||||
isCompleted={false}
|
||||
steps={STEP_LIST}
|
||||
storageKey={ONBOARDING_UPLOAD_STEPS_KEY}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
};
|
||||
|
||||
export default OnboardingUpload;
|
||||
|
|
|
|||
|
|
@ -9,161 +9,161 @@ import type { ProviderHealthResponse } from "@/app/api/queries/useProviderHealth
|
|||
import AnthropicLogo from "@/components/icons/anthropic-logo";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
AnthropicSettingsForm,
|
||||
type AnthropicSettingsFormData,
|
||||
AnthropicSettingsForm,
|
||||
type AnthropicSettingsFormData,
|
||||
} from "./anthropic-settings-form";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const AnthropicSettingsDialog = ({
|
||||
open,
|
||||
setOpen,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const methods = useForm<AnthropicSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
},
|
||||
});
|
||||
const methods = useForm<AnthropicSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit, watch } = methods;
|
||||
const apiKey = watch("apiKey");
|
||||
const { handleSubmit, watch } = methods;
|
||||
const apiKey = watch("apiKey");
|
||||
|
||||
const { refetch: validateCredentials } = useGetAnthropicModelsQuery(
|
||||
{
|
||||
apiKey: apiKey,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
const { refetch: validateCredentials } = useGetAnthropicModelsQuery(
|
||||
{
|
||||
apiKey: apiKey,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "anthropic",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "anthropic",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
|
||||
toast.message("Anthropic successfully configured", {
|
||||
description: "You can now access the provided language models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <AnthropicLogo className="w-4 h-4 text-[#D97757]" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.message("Anthropic successfully configured", {
|
||||
description: "You can now access the provided language models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <AnthropicLogo className="w-4 h-4 text-[#D97757]" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: AnthropicSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
const onSubmit = async (data: AnthropicSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
|
||||
// Only validate if a new API key was entered
|
||||
if (data.apiKey) {
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
// Only validate if a new API key was entered
|
||||
if (data.apiKey) {
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const payload: {
|
||||
anthropic_api_key?: string;
|
||||
} = {};
|
||||
const payload: {
|
||||
anthropic_api_key?: string;
|
||||
} = {};
|
||||
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.anthropic_api_key = data.apiKey;
|
||||
}
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.anthropic_api_key = data.apiKey;
|
||||
}
|
||||
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<AnthropicLogo className="text-black" />
|
||||
</div>
|
||||
Anthropic Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<AnthropicLogo className="text-black" />
|
||||
</div>
|
||||
Anthropic Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<AnthropicSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
<AnthropicSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnthropicSettingsDialog;
|
||||
|
|
|
|||
|
|
@ -10,162 +10,162 @@ import type { ProviderHealthResponse } from "@/app/api/queries/useProviderHealth
|
|||
import OllamaLogo from "@/components/icons/ollama-logo";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useAuth } from "@/contexts/auth-context";
|
||||
import {
|
||||
OllamaSettingsForm,
|
||||
type OllamaSettingsFormData,
|
||||
OllamaSettingsForm,
|
||||
type OllamaSettingsFormData,
|
||||
} from "./ollama-settings-form";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const OllamaSettingsDialog = ({
|
||||
open,
|
||||
setOpen,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) => {
|
||||
const { isAuthenticated, isNoAuthMode } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
const { isAuthenticated, isNoAuthMode } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const { data: settings = {} } = useGetSettingsQuery({
|
||||
enabled: isAuthenticated || isNoAuthMode,
|
||||
});
|
||||
const { data: settings = {} } = useGetSettingsQuery({
|
||||
enabled: isAuthenticated || isNoAuthMode,
|
||||
});
|
||||
|
||||
const isOllamaConfigured = settings.providers?.ollama?.configured === true;
|
||||
const isOllamaConfigured = settings.providers?.ollama?.configured === true;
|
||||
|
||||
const methods = useForm<OllamaSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
endpoint: isOllamaConfigured
|
||||
? settings.providers?.ollama?.endpoint
|
||||
: "http://localhost:11434",
|
||||
},
|
||||
});
|
||||
const methods = useForm<OllamaSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
endpoint: isOllamaConfigured
|
||||
? settings.providers?.ollama?.endpoint
|
||||
: "http://localhost:11434",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit, watch } = methods;
|
||||
const endpoint = watch("endpoint");
|
||||
const { handleSubmit, watch } = methods;
|
||||
const endpoint = watch("endpoint");
|
||||
|
||||
const { refetch: validateCredentials } = useGetOllamaModelsQuery(
|
||||
{
|
||||
endpoint: endpoint,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
const { refetch: validateCredentials } = useGetOllamaModelsQuery(
|
||||
{
|
||||
endpoint: endpoint,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "ollama",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "ollama",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
|
||||
toast.message("Ollama successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <OllamaLogo className="w-4 h-4" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.message("Ollama successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <OllamaLogo className="w-4 h-4" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: OllamaSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
const onSubmit = async (data: OllamaSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
|
||||
// Validate endpoint by fetching models
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
// Validate endpoint by fetching models
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
settingsMutation.mutate({
|
||||
ollama_endpoint: data.endpoint,
|
||||
});
|
||||
};
|
||||
settingsMutation.mutate({
|
||||
ollama_endpoint: data.endpoint,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<OllamaLogo className="text-black" />
|
||||
</div>
|
||||
Ollama Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<OllamaLogo className="text-black" />
|
||||
</div>
|
||||
Ollama Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<OllamaSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
<OllamaSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default OllamaSettingsDialog;
|
||||
|
|
|
|||
|
|
@ -9,162 +9,162 @@ import type { ProviderHealthResponse } from "@/app/api/queries/useProviderHealth
|
|||
import OpenAILogo from "@/components/icons/openai-logo";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
OpenAISettingsForm,
|
||||
type OpenAISettingsFormData,
|
||||
OpenAISettingsForm,
|
||||
type OpenAISettingsFormData,
|
||||
} from "./openai-settings-form";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const OpenAISettingsDialog = ({
|
||||
open,
|
||||
setOpen,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const methods = useForm<OpenAISettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
},
|
||||
});
|
||||
const methods = useForm<OpenAISettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit, watch } = methods;
|
||||
const apiKey = watch("apiKey");
|
||||
const { handleSubmit, watch } = methods;
|
||||
const apiKey = watch("apiKey");
|
||||
|
||||
const { refetch: validateCredentials } = useGetOpenAIModelsQuery(
|
||||
{
|
||||
apiKey: apiKey,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
const { refetch: validateCredentials } = useGetOpenAIModelsQuery(
|
||||
{
|
||||
apiKey: apiKey,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "openai",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "openai",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
|
||||
toast.message("OpenAI successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <OpenAILogo className="w-4 h-4" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.message("OpenAI successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <OpenAILogo className="w-4 h-4" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: OpenAISettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
const onSubmit = async (data: OpenAISettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
|
||||
// Only validate if a new API key was entered
|
||||
if (data.apiKey) {
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
// Only validate if a new API key was entered
|
||||
if (data.apiKey) {
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const payload: {
|
||||
openai_api_key?: string;
|
||||
} = {};
|
||||
const payload: {
|
||||
openai_api_key?: string;
|
||||
} = {};
|
||||
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.openai_api_key = data.apiKey;
|
||||
}
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.openai_api_key = data.apiKey;
|
||||
}
|
||||
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<OpenAILogo className="text-black" />
|
||||
</div>
|
||||
OpenAI Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<OpenAILogo className="text-black" />
|
||||
</div>
|
||||
OpenAI Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<OpenAISettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
<OpenAISettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default OpenAISettingsDialog;
|
||||
|
|
|
|||
|
|
@ -9,171 +9,171 @@ import type { ProviderHealthResponse } from "@/app/api/queries/useProviderHealth
|
|||
import IBMLogo from "@/components/icons/ibm-logo";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
WatsonxSettingsForm,
|
||||
type WatsonxSettingsFormData,
|
||||
WatsonxSettingsForm,
|
||||
type WatsonxSettingsFormData,
|
||||
} from "./watsonx-settings-form";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const WatsonxSettingsDialog = ({
|
||||
open,
|
||||
setOpen,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [validationError, setValidationError] = useState<Error | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const methods = useForm<WatsonxSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
endpoint: "https://us-south.ml.cloud.ibm.com",
|
||||
apiKey: "",
|
||||
projectId: "",
|
||||
},
|
||||
});
|
||||
const methods = useForm<WatsonxSettingsFormData>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
endpoint: "https://us-south.ml.cloud.ibm.com",
|
||||
apiKey: "",
|
||||
projectId: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit, watch } = methods;
|
||||
const endpoint = watch("endpoint");
|
||||
const apiKey = watch("apiKey");
|
||||
const projectId = watch("projectId");
|
||||
const { handleSubmit, watch } = methods;
|
||||
const endpoint = watch("endpoint");
|
||||
const apiKey = watch("apiKey");
|
||||
const projectId = watch("projectId");
|
||||
|
||||
const { refetch: validateCredentials } = useGetIBMModelsQuery(
|
||||
{
|
||||
endpoint: endpoint,
|
||||
apiKey: apiKey,
|
||||
projectId: projectId,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
const { refetch: validateCredentials } = useGetIBMModelsQuery(
|
||||
{
|
||||
endpoint: endpoint,
|
||||
apiKey: apiKey,
|
||||
projectId: projectId,
|
||||
},
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "watsonx",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
const settingsMutation = useUpdateSettingsMutation({
|
||||
onSuccess: () => {
|
||||
// Update provider health cache to healthy since backend validated the setup
|
||||
const healthData: ProviderHealthResponse = {
|
||||
status: "healthy",
|
||||
message: "Provider is configured and working correctly",
|
||||
provider: "watsonx",
|
||||
};
|
||||
queryClient.setQueryData(["provider", "health"], healthData);
|
||||
|
||||
toast.message("IBM watsonx.ai successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <IBMLogo className="w-4 h-4 text-[#1063FE]" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.message("IBM watsonx.ai successfully configured", {
|
||||
description:
|
||||
"You can now access the provided language and embedding models.",
|
||||
duration: Infinity,
|
||||
closeButton: true,
|
||||
icon: <IBMLogo className="w-4 h-4 text-[#1063FE]" />,
|
||||
action: {
|
||||
label: "Settings",
|
||||
onClick: () => {
|
||||
router.push("/settings?focusLlmModel=true");
|
||||
},
|
||||
},
|
||||
});
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: WatsonxSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
const onSubmit = async (data: WatsonxSettingsFormData) => {
|
||||
// Clear any previous validation errors
|
||||
setValidationError(null);
|
||||
|
||||
// Validate credentials by fetching models
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
// Validate credentials by fetching models
|
||||
setIsValidating(true);
|
||||
const result = await validateCredentials();
|
||||
setIsValidating(false);
|
||||
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.isError) {
|
||||
setValidationError(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: {
|
||||
watsonx_endpoint: string;
|
||||
watsonx_api_key?: string;
|
||||
watsonx_project_id: string;
|
||||
} = {
|
||||
watsonx_endpoint: data.endpoint,
|
||||
watsonx_project_id: data.projectId,
|
||||
};
|
||||
const payload: {
|
||||
watsonx_endpoint: string;
|
||||
watsonx_api_key?: string;
|
||||
watsonx_project_id: string;
|
||||
} = {
|
||||
watsonx_endpoint: data.endpoint,
|
||||
watsonx_project_id: data.projectId,
|
||||
};
|
||||
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.watsonx_api_key = data.apiKey;
|
||||
}
|
||||
// Only include api_key if a value was entered
|
||||
if (data.apiKey) {
|
||||
payload.watsonx_api_key = data.apiKey;
|
||||
}
|
||||
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
// Submit the update
|
||||
settingsMutation.mutate(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent autoFocus={false} className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<IBMLogo className="text-black" />
|
||||
</div>
|
||||
IBM watsonx.ai Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent autoFocus={false} className="max-w-2xl">
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-4">
|
||||
<DialogHeader className="mb-2">
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded flex items-center justify-center bg-white border">
|
||||
<IBMLogo className="text-black" />
|
||||
</div>
|
||||
IBM watsonx.ai Setup
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<WatsonxSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
<WatsonxSettingsForm
|
||||
modelsError={validationError}
|
||||
isLoadingModels={isValidating}
|
||||
/>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
<AnimatePresence mode="wait">
|
||||
{settingsMutation.isError && (
|
||||
<motion.div
|
||||
key="error"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
>
|
||||
<p className="rounded-lg border border-destructive p-4">
|
||||
{settingsMutation.error?.message}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={settingsMutation.isPending || isValidating}
|
||||
>
|
||||
{settingsMutation.isPending
|
||||
? "Saving..."
|
||||
: isValidating
|
||||
? "Validating..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default WatsonxSettingsDialog;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -4,8 +4,8 @@ import { motion } from "framer-motion";
|
|||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
type ChatConversation,
|
||||
useGetConversationsQuery,
|
||||
type ChatConversation,
|
||||
useGetConversationsQuery,
|
||||
} from "@/app/api/queries/useGetConversationsQuery";
|
||||
import type { Settings } from "@/app/api/queries/useGetSettingsQuery";
|
||||
import { OnboardingContent } from "@/app/onboarding/_components/onboarding-content";
|
||||
|
|
@ -16,223 +16,223 @@ import { Navigation } from "@/components/navigation";
|
|||
import { useAuth } from "@/contexts/auth-context";
|
||||
import { useChat } from "@/contexts/chat-context";
|
||||
import {
|
||||
ANIMATION_DURATION,
|
||||
HEADER_HEIGHT,
|
||||
ONBOARDING_ASSISTANT_MESSAGE_KEY,
|
||||
ONBOARDING_CARD_STEPS_KEY,
|
||||
ONBOARDING_SELECTED_NUDGE_KEY,
|
||||
ONBOARDING_STEP_KEY,
|
||||
ONBOARDING_UPLOAD_STEPS_KEY,
|
||||
SIDEBAR_WIDTH,
|
||||
TOTAL_ONBOARDING_STEPS,
|
||||
ANIMATION_DURATION,
|
||||
HEADER_HEIGHT,
|
||||
ONBOARDING_ASSISTANT_MESSAGE_KEY,
|
||||
ONBOARDING_CARD_STEPS_KEY,
|
||||
ONBOARDING_SELECTED_NUDGE_KEY,
|
||||
ONBOARDING_STEP_KEY,
|
||||
ONBOARDING_UPLOAD_STEPS_KEY,
|
||||
SIDEBAR_WIDTH,
|
||||
TOTAL_ONBOARDING_STEPS,
|
||||
} from "@/lib/constants";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function ChatRenderer({
|
||||
settings,
|
||||
children,
|
||||
settings,
|
||||
children,
|
||||
}: {
|
||||
settings: Settings | undefined;
|
||||
children: React.ReactNode;
|
||||
settings: Settings | undefined;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const { isAuthenticated, isNoAuthMode } = useAuth();
|
||||
const {
|
||||
endpoint,
|
||||
refreshTrigger,
|
||||
refreshConversations,
|
||||
startNewConversation,
|
||||
} = useChat();
|
||||
const pathname = usePathname();
|
||||
const { isAuthenticated, isNoAuthMode } = useAuth();
|
||||
const {
|
||||
endpoint,
|
||||
refreshTrigger,
|
||||
refreshConversations,
|
||||
startNewConversation,
|
||||
} = useChat();
|
||||
|
||||
// Initialize onboarding state based on local storage and settings
|
||||
const [currentStep, setCurrentStep] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 0;
|
||||
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
|
||||
return savedStep !== null ? parseInt(savedStep, 10) : 0;
|
||||
});
|
||||
// Initialize onboarding state based on local storage and settings
|
||||
const [currentStep, setCurrentStep] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 0;
|
||||
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
|
||||
return savedStep !== null ? parseInt(savedStep, 10) : 0;
|
||||
});
|
||||
|
||||
const [showLayout, setShowLayout] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false;
|
||||
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
|
||||
// Show layout if settings.edited is true and if no onboarding step is saved
|
||||
const isEdited = settings?.edited ?? true;
|
||||
return isEdited ? savedStep === null : false;
|
||||
});
|
||||
const [showLayout, setShowLayout] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false;
|
||||
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
|
||||
// Show layout if settings.edited is true and if no onboarding step is saved
|
||||
const isEdited = settings?.edited ?? true;
|
||||
return isEdited ? savedStep === null : false;
|
||||
});
|
||||
|
||||
// Only fetch conversations on chat page
|
||||
const isOnChatPage = pathname === "/" || pathname === "/chat";
|
||||
const { data: conversations = [], isLoading: isConversationsLoading } =
|
||||
useGetConversationsQuery(endpoint, refreshTrigger, {
|
||||
enabled: isOnChatPage && (isAuthenticated || isNoAuthMode),
|
||||
}) as { data: ChatConversation[]; isLoading: boolean };
|
||||
// Only fetch conversations on chat page
|
||||
const isOnChatPage = pathname === "/" || pathname === "/chat";
|
||||
const { data: conversations = [], isLoading: isConversationsLoading } =
|
||||
useGetConversationsQuery(endpoint, refreshTrigger, {
|
||||
enabled: isOnChatPage && (isAuthenticated || isNoAuthMode),
|
||||
}) as { data: ChatConversation[]; isLoading: boolean };
|
||||
|
||||
const handleNewConversation = () => {
|
||||
refreshConversations();
|
||||
startNewConversation();
|
||||
};
|
||||
const handleNewConversation = () => {
|
||||
refreshConversations();
|
||||
startNewConversation();
|
||||
};
|
||||
|
||||
// Save current step to local storage whenever it changes
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && !showLayout) {
|
||||
localStorage.setItem(ONBOARDING_STEP_KEY, currentStep.toString());
|
||||
}
|
||||
}, [currentStep, showLayout]);
|
||||
// Save current step to local storage whenever it changes
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && !showLayout) {
|
||||
localStorage.setItem(ONBOARDING_STEP_KEY, currentStep.toString());
|
||||
}
|
||||
}, [currentStep, showLayout]);
|
||||
|
||||
const handleStepComplete = () => {
|
||||
if (currentStep < TOTAL_ONBOARDING_STEPS - 1) {
|
||||
setCurrentStep(currentStep + 1);
|
||||
} else {
|
||||
// Onboarding is complete - remove from local storage and show layout
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem(ONBOARDING_STEP_KEY);
|
||||
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_CARD_STEPS_KEY);
|
||||
localStorage.removeItem(ONBOARDING_UPLOAD_STEPS_KEY);
|
||||
}
|
||||
setShowLayout(true);
|
||||
}
|
||||
};
|
||||
const handleStepComplete = () => {
|
||||
if (currentStep < TOTAL_ONBOARDING_STEPS - 1) {
|
||||
setCurrentStep(currentStep + 1);
|
||||
} else {
|
||||
// Onboarding is complete - remove from local storage and show layout
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem(ONBOARDING_STEP_KEY);
|
||||
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_CARD_STEPS_KEY);
|
||||
localStorage.removeItem(ONBOARDING_UPLOAD_STEPS_KEY);
|
||||
}
|
||||
setShowLayout(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStepBack = () => {
|
||||
if (currentStep > 0) {
|
||||
setCurrentStep(currentStep - 1);
|
||||
}
|
||||
};
|
||||
const handleStepBack = () => {
|
||||
if (currentStep > 0) {
|
||||
setCurrentStep(currentStep - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSkipOnboarding = () => {
|
||||
// Skip onboarding by marking it as complete
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem(ONBOARDING_STEP_KEY);
|
||||
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_CARD_STEPS_KEY);
|
||||
localStorage.removeItem(ONBOARDING_UPLOAD_STEPS_KEY);
|
||||
}
|
||||
setShowLayout(true);
|
||||
};
|
||||
const handleSkipOnboarding = () => {
|
||||
// Skip onboarding by marking it as complete
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem(ONBOARDING_STEP_KEY);
|
||||
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
|
||||
localStorage.removeItem(ONBOARDING_CARD_STEPS_KEY);
|
||||
localStorage.removeItem(ONBOARDING_UPLOAD_STEPS_KEY);
|
||||
}
|
||||
setShowLayout(true);
|
||||
};
|
||||
|
||||
// List of paths with smaller max-width
|
||||
const smallWidthPaths = ["/settings", "/upload"];
|
||||
const isSmallWidthPath = smallWidthPaths.some((path) =>
|
||||
pathname.startsWith(path),
|
||||
);
|
||||
// List of paths with smaller max-width
|
||||
const smallWidthPaths = ["/settings", "/upload"];
|
||||
const isSmallWidthPath = smallWidthPaths.some((path) =>
|
||||
pathname.startsWith(path),
|
||||
);
|
||||
|
||||
const x = showLayout ? "0px" : `calc(-${SIDEBAR_WIDTH / 2}px + 50vw)`;
|
||||
const y = showLayout ? "0px" : `calc(-${HEADER_HEIGHT / 2}px + 50vh)`;
|
||||
const translateY = showLayout ? "0px" : `-50vh`;
|
||||
const translateX = showLayout ? "0px" : `-50vw`;
|
||||
const x = showLayout ? "0px" : `calc(-${SIDEBAR_WIDTH / 2}px + 50vw)`;
|
||||
const y = showLayout ? "0px" : `calc(-${HEADER_HEIGHT / 2}px + 50vh)`;
|
||||
const translateY = showLayout ? "0px" : `-50vh`;
|
||||
const translateX = showLayout ? "0px" : `-50vw`;
|
||||
|
||||
// For all other pages, render with Langflow-styled navigation and task menu
|
||||
return (
|
||||
<>
|
||||
<AnimatedConditional
|
||||
className="[grid-area:header] bg-background border-b"
|
||||
vertical
|
||||
slide
|
||||
isOpen={showLayout}
|
||||
delay={ANIMATION_DURATION / 2}
|
||||
>
|
||||
<Header />
|
||||
</AnimatedConditional>
|
||||
// For all other pages, render with Langflow-styled navigation and task menu
|
||||
return (
|
||||
<>
|
||||
<AnimatedConditional
|
||||
className="[grid-area:header] bg-background border-b"
|
||||
vertical
|
||||
slide
|
||||
isOpen={showLayout}
|
||||
delay={ANIMATION_DURATION / 2}
|
||||
>
|
||||
<Header />
|
||||
</AnimatedConditional>
|
||||
|
||||
{/* Sidebar Navigation */}
|
||||
<AnimatedConditional
|
||||
isOpen={showLayout}
|
||||
slide
|
||||
className={`border-r bg-background overflow-hidden [grid-area:nav] w-[${SIDEBAR_WIDTH}px]`}
|
||||
>
|
||||
{showLayout && (
|
||||
<Navigation
|
||||
conversations={conversations}
|
||||
isConversationsLoading={isConversationsLoading}
|
||||
onNewConversation={handleNewConversation}
|
||||
/>
|
||||
)}
|
||||
</AnimatedConditional>
|
||||
{/* Sidebar Navigation */}
|
||||
<AnimatedConditional
|
||||
isOpen={showLayout}
|
||||
slide
|
||||
className={`border-r bg-background overflow-hidden [grid-area:nav] w-[${SIDEBAR_WIDTH}px]`}
|
||||
>
|
||||
{showLayout && (
|
||||
<Navigation
|
||||
conversations={conversations}
|
||||
isConversationsLoading={isConversationsLoading}
|
||||
onNewConversation={handleNewConversation}
|
||||
/>
|
||||
)}
|
||||
</AnimatedConditional>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="overflow-hidden w-full flex items-center justify-center [grid-area:main]">
|
||||
<motion.div
|
||||
initial={{
|
||||
width: showLayout ? "100%" : "100vw",
|
||||
height: showLayout ? "100%" : "100vh",
|
||||
x: x,
|
||||
y: y,
|
||||
translateX: translateX,
|
||||
translateY: translateY,
|
||||
}}
|
||||
animate={{
|
||||
width: showLayout ? "100%" : "850px",
|
||||
borderRadius: showLayout ? "0" : "16px",
|
||||
border: showLayout ? "0" : "1px solid hsl(var(--border))",
|
||||
height: showLayout ? "100%" : "800px",
|
||||
x: x,
|
||||
y: y,
|
||||
translateX: translateX,
|
||||
translateY: translateY,
|
||||
}}
|
||||
transition={{
|
||||
duration: ANIMATION_DURATION,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
className={cn(
|
||||
"flex h-full w-full max-w-full max-h-full items-center justify-center overflow-y-auto",
|
||||
!showLayout &&
|
||||
"absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]",
|
||||
showLayout && !isOnChatPage && "bg-background",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"h-full bg-background w-full",
|
||||
showLayout && !isOnChatPage && "p-6 container",
|
||||
showLayout && isSmallWidthPath && "max-w-[850px] ml-0",
|
||||
!showLayout && "p-0 py-2",
|
||||
)}
|
||||
>
|
||||
<motion.div
|
||||
initial={{
|
||||
opacity: showLayout ? 1 : 0,
|
||||
}}
|
||||
animate={{
|
||||
opacity: "100%",
|
||||
}}
|
||||
transition={{
|
||||
duration: ANIMATION_DURATION,
|
||||
ease: "easeOut",
|
||||
delay: ANIMATION_DURATION,
|
||||
}}
|
||||
className={cn("w-full h-full")}
|
||||
>
|
||||
{showLayout && (
|
||||
<div className={cn("w-full h-full", !showLayout && "hidden")}>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
{!showLayout && (
|
||||
<OnboardingContent
|
||||
handleStepComplete={handleStepComplete}
|
||||
handleStepBack={handleStepBack}
|
||||
currentStep={currentStep}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
</motion.div>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: showLayout ? 0 : 1, y: showLayout ? 20 : 0 }}
|
||||
transition={{ duration: ANIMATION_DURATION, ease: "easeOut" }}
|
||||
className={cn("absolute bottom-6 left-0 right-0")}
|
||||
>
|
||||
<ProgressBar
|
||||
currentStep={currentStep}
|
||||
totalSteps={TOTAL_ONBOARDING_STEPS}
|
||||
onSkip={handleSkipOnboarding}
|
||||
/>
|
||||
</motion.div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
{/* Main Content */}
|
||||
<main className="overflow-hidden w-full flex items-center justify-center [grid-area:main]">
|
||||
<motion.div
|
||||
initial={{
|
||||
width: showLayout ? "100%" : "100vw",
|
||||
height: showLayout ? "100%" : "100vh",
|
||||
x: x,
|
||||
y: y,
|
||||
translateX: translateX,
|
||||
translateY: translateY,
|
||||
}}
|
||||
animate={{
|
||||
width: showLayout ? "100%" : "850px",
|
||||
borderRadius: showLayout ? "0" : "16px",
|
||||
border: showLayout ? "0" : "1px solid hsl(var(--border))",
|
||||
height: showLayout ? "100%" : "800px",
|
||||
x: x,
|
||||
y: y,
|
||||
translateX: translateX,
|
||||
translateY: translateY,
|
||||
}}
|
||||
transition={{
|
||||
duration: ANIMATION_DURATION,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
className={cn(
|
||||
"flex h-full w-full max-w-full max-h-full items-center justify-center overflow-y-auto",
|
||||
!showLayout &&
|
||||
"absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]",
|
||||
showLayout && !isOnChatPage && "bg-background",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"h-full bg-background w-full",
|
||||
showLayout && !isOnChatPage && "p-6 container",
|
||||
showLayout && isSmallWidthPath && "max-w-[850px] ml-0",
|
||||
!showLayout && "p-0 py-2",
|
||||
)}
|
||||
>
|
||||
<motion.div
|
||||
initial={{
|
||||
opacity: showLayout ? 1 : 0,
|
||||
}}
|
||||
animate={{
|
||||
opacity: "100%",
|
||||
}}
|
||||
transition={{
|
||||
duration: ANIMATION_DURATION,
|
||||
ease: "easeOut",
|
||||
delay: ANIMATION_DURATION,
|
||||
}}
|
||||
className={cn("w-full h-full")}
|
||||
>
|
||||
{showLayout && (
|
||||
<div className={cn("w-full h-full", !showLayout && "hidden")}>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
{!showLayout && (
|
||||
<OnboardingContent
|
||||
handleStepComplete={handleStepComplete}
|
||||
handleStepBack={handleStepBack}
|
||||
currentStep={currentStep}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
</motion.div>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: showLayout ? 0 : 1, y: showLayout ? 20 : 0 }}
|
||||
transition={{ duration: ANIMATION_DURATION, ease: "easeOut" }}
|
||||
className={cn("absolute bottom-6 left-0 right-0")}
|
||||
>
|
||||
<ProgressBar
|
||||
currentStep={currentStep}
|
||||
totalSteps={TOTAL_ONBOARDING_STEPS}
|
||||
onSkip={handleSkipOnboarding}
|
||||
/>
|
||||
</motion.div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -201,29 +201,29 @@ 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 {
|
||||
id: item.id,
|
||||
name: item.name || `${this.getProviderName()} File`,
|
||||
|
|
|
|||
|
|
@ -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) => (
|
||||
<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>
|
||||
))
|
||||
[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 ? (
|
||||
<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) => {
|
||||
setCurrentConversationId(conversation.response_id);
|
||||
setEndpoint(conversation.endpoint);
|
||||
// Store the full conversation data for the chat page to use
|
||||
setConversationData(conversation);
|
||||
// Clear placeholder when loading a real conversation
|
||||
setPlaceholderConversation(null);
|
||||
setConversationLoaded(true);
|
||||
// Clear conversation docs to prevent duplicates when switching conversations
|
||||
setConversationDocs([]);
|
||||
}, []);
|
||||
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,
|
||||
],
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ export function useChatStreaming({
|
|||
// Set up timeout to detect stuck/hanging requests
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
let hasReceivedData = false;
|
||||
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
|
|
@ -53,7 +53,7 @@ export function useChatStreaming({
|
|||
const controller = new AbortController();
|
||||
streamAbortRef.current = controller;
|
||||
const thisStreamId = ++streamIdRef.current;
|
||||
|
||||
|
||||
// Set up timeout (60 seconds for initial response, then extended as data comes in)
|
||||
const startTimeout = () => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
|
|
@ -65,7 +65,7 @@ export function useChatStreaming({
|
|||
}
|
||||
}, 60000); // 60 second timeout
|
||||
};
|
||||
|
||||
|
||||
startTimeout();
|
||||
|
||||
const requestBody: {
|
||||
|
|
@ -135,7 +135,7 @@ export function useChatStreaming({
|
|||
if (controller.signal.aborted || thisStreamId !== streamIdRef.current)
|
||||
break;
|
||||
if (done) break;
|
||||
|
||||
|
||||
// Reset timeout on each chunk received
|
||||
hasReceivedData = true;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
|
|
@ -464,10 +464,15 @@ export function useChatStreaming({
|
|||
reader.releaseLock();
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
|
|
@ -491,29 +496,38 @@ export function useChatStreaming({
|
|||
} catch (error) {
|
||||
// Clean up timeout
|
||||
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;
|
||||
}
|
||||
|
||||
console.error("Chat stream error:", error);
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
onError?.(error as Error);
|
||||
|
||||
const errorMessageObj: Message = {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue