Compare commits

...
Sign in to create a new pull request.

13 commits

12 changed files with 1132 additions and 1148 deletions

View file

@ -1,4 +1,4 @@
FROM langflowai/langflow-nightly:1.6.3.dev1 FROM langflowai/langflow-nightly:1.7.0.dev5
EXPOSE 7860 EXPOSE 7860

View file

@ -91,7 +91,7 @@ services:
langflow: langflow:
volumes: volumes:
- ./flows:/app/flows:U,z - ./flows:/app/flows:U,z
image: langflowai/langflow-nightly:${LANGFLOW_VERSION:-1.7.0.dev5} image: phact/openrag-langflow:${LANGFLOW_VERSION:-latest}
# build: # build:
# context: . # context: .
# dockerfile: Dockerfile.langflow # dockerfile: Dockerfile.langflow

View file

@ -76,6 +76,11 @@ export const useGetNudgesQuery = (
{ {
queryKey: ["nudges", chatId, filters, limit, scoreThreshold], queryKey: ["nudges", chatId, filters, limit, scoreThreshold],
queryFn: getNudges, queryFn: getNudges,
refetchInterval: (query) => {
// If data is empty, refetch every 5 seconds
const data = query.state.data;
return Array.isArray(data) && data.length === 0 ? 5000 : false;
},
...options, ...options,
}, },
queryClient, queryClient,

View file

@ -782,7 +782,11 @@ function ChatPage() {
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, userMessage]); if (messages.length === 1) {
setMessages([userMessage]);
} else {
setMessages((prev) => [...prev, userMessage]);
}
setInput(""); setInput("");
setLoading(true); setLoading(true);
setIsFilterHighlighted(false); setIsFilterHighlighted(false);

View file

@ -5,210 +5,211 @@ import { CheckIcon, XIcon } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import AnimatedProcessingIcon from "@/components/icons/animated-processing-icon"; import AnimatedProcessingIcon from "@/components/icons/animated-processing-icon";
import { import {
Accordion, Accordion,
AccordionContent, AccordionContent,
AccordionItem, AccordionItem,
AccordionTrigger, AccordionTrigger,
} from "@/components/ui/accordion"; } from "@/components/ui/accordion";
import { ONBOARDING_CARD_STEPS_KEY } from "@/lib/constants";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export function AnimatedProviderSteps({ export function AnimatedProviderSteps({
currentStep, currentStep,
isCompleted, isCompleted,
setCurrentStep, setCurrentStep,
steps, steps,
storageKey = "provider-steps", storageKey = ONBOARDING_CARD_STEPS_KEY,
processingStartTime, processingStartTime,
hasError = false, hasError = false,
}: { }: {
currentStep: number; currentStep: number;
isCompleted: boolean; isCompleted: boolean;
setCurrentStep: (step: number) => void; setCurrentStep: (step: number) => void;
steps: string[]; steps: string[];
storageKey?: string; storageKey?: string;
processingStartTime?: number | null; processingStartTime?: number | null;
hasError?: boolean; hasError?: boolean;
}) { }) {
const [startTime, setStartTime] = useState<number | null>(null); const [startTime, setStartTime] = useState<number | null>(null);
const [elapsedTime, setElapsedTime] = useState<number>(0); const [elapsedTime, setElapsedTime] = useState<number>(0);
// Initialize start time from prop or local storage // Initialize start time from prop or local storage
useEffect(() => { useEffect(() => {
const storedElapsedTime = localStorage.getItem(`${storageKey}-elapsed`); const storedElapsedTime = localStorage.getItem(storageKey);
if (isCompleted && storedElapsedTime) { if (isCompleted && storedElapsedTime) {
// If completed, use stored elapsed time // If completed, use stored elapsed time
setElapsedTime(parseFloat(storedElapsedTime)); setElapsedTime(parseFloat(storedElapsedTime));
} else if (processingStartTime) { } else if (processingStartTime) {
// Use the start time passed from parent (when user clicked Complete) // Use the start time passed from parent (when user clicked Complete)
setStartTime(processingStartTime); setStartTime(processingStartTime);
} }
}, [storageKey, isCompleted, processingStartTime]); }, [storageKey, isCompleted, processingStartTime]);
// Progress through steps // Progress through steps
useEffect(() => { useEffect(() => {
if (currentStep < steps.length - 1 && !isCompleted) { if (currentStep < steps.length - 1 && !isCompleted) {
const interval = setInterval(() => { const interval = setInterval(() => {
setCurrentStep(currentStep + 1); setCurrentStep(currentStep + 1);
}, 1500); }, 1500);
return () => clearInterval(interval); return () => clearInterval(interval);
} }
}, [currentStep, setCurrentStep, steps, isCompleted]); }, [currentStep, setCurrentStep, steps, isCompleted]);
// Calculate and store elapsed time when completed // Calculate and store elapsed time when completed
useEffect(() => { useEffect(() => {
if (isCompleted && startTime) { if (isCompleted && startTime) {
const elapsed = Date.now() - startTime; const elapsed = Date.now() - startTime;
setElapsedTime(elapsed); setElapsedTime(elapsed);
localStorage.setItem(`${storageKey}-elapsed`, elapsed.toString()); localStorage.setItem(storageKey, elapsed.toString());
} }
}, [isCompleted, startTime, storageKey]); }, [isCompleted, startTime, storageKey]);
const isDone = currentStep >= steps.length && !isCompleted && !hasError; const isDone = currentStep >= steps.length && !isCompleted && !hasError;
return ( return (
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{!isCompleted ? ( {!isCompleted ? (
<motion.div <motion.div
key="processing" key="processing"
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
transition={{ duration: 0.3 }} transition={{ duration: 0.3 }}
className="flex flex-col gap-2" className="flex flex-col gap-2"
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div <div
className={cn( className={cn(
"transition-all duration-300 relative", "transition-all duration-300 relative",
isDone || hasError ? "w-3.5 h-3.5" : "w-6 h-6", isDone || hasError ? "w-3.5 h-3.5" : "w-6 h-6",
)} )}
> >
<CheckIcon <CheckIcon
className={cn( className={cn(
"text-accent-emerald-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150", "text-accent-emerald-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
isDone ? "opacity-100" : "opacity-0", isDone ? "opacity-100" : "opacity-0",
)} )}
/> />
<XIcon <XIcon
className={cn( className={cn(
"text-accent-red-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150", "text-accent-red-foreground shrink-0 w-3.5 h-3.5 absolute inset-0 transition-all duration-150",
hasError ? "opacity-100" : "opacity-0", hasError ? "opacity-100" : "opacity-0",
)} )}
/> />
<AnimatedProcessingIcon <AnimatedProcessingIcon
className={cn( className={cn(
"text-current shrink-0 absolute inset-0 transition-all duration-150", "text-current shrink-0 absolute inset-0 transition-all duration-150",
isDone || hasError ? "opacity-0" : "opacity-100", isDone || hasError ? "opacity-0" : "opacity-100",
)} )}
/> />
</div> </div>
<span className="!text-mmd font-medium text-muted-foreground"> <span className="!text-mmd font-medium text-muted-foreground">
{hasError ? "Error" : isDone ? "Done" : "Thinking"} {hasError ? "Error" : isDone ? "Done" : "Thinking"}
</span> </span>
</div> </div>
<div className="overflow-hidden"> <div className="overflow-hidden">
<AnimatePresence> <AnimatePresence>
{!isDone && !hasError && ( {!isDone && !hasError && (
<motion.div <motion.div
initial={{ opacity: 1, y: 0, height: "auto" }} initial={{ opacity: 1, y: 0, height: "auto" }}
exit={{ opacity: 0, y: -24, height: 0 }} exit={{ opacity: 0, y: -24, height: 0 }}
transition={{ duration: 0.4, ease: "easeInOut" }} transition={{ duration: 0.4, ease: "easeInOut" }}
className="flex items-center gap-4 overflow-y-hidden relative h-6" className="flex items-center gap-4 overflow-y-hidden relative h-6"
> >
<div className="w-px h-6 bg-border ml-3" /> <div className="w-px h-6 bg-border ml-3" />
<div className="relative h-5 w-full"> <div className="relative h-5 w-full">
<AnimatePresence mode="sync" initial={false}> <AnimatePresence mode="sync" initial={false}>
<motion.span <motion.span
key={currentStep} key={currentStep}
initial={{ y: 24, opacity: 0 }} initial={{ y: 24, opacity: 0 }}
animate={{ y: 0, opacity: 1 }} animate={{ y: 0, opacity: 1 }}
exit={{ y: -24, opacity: 0 }} exit={{ y: -24, opacity: 0 }}
transition={{ duration: 0.3, ease: "easeInOut" }} transition={{ duration: 0.3, ease: "easeInOut" }}
className="text-mmd font-medium text-primary absolute left-0" className="text-mmd font-medium text-primary absolute left-0"
> >
{steps[currentStep]} {steps[currentStep]}
</motion.span> </motion.span>
</AnimatePresence> </AnimatePresence>
</div> </div>
</motion.div> </motion.div>
)} )}
</AnimatePresence> </AnimatePresence>
</div> </div>
</motion.div> </motion.div>
) : ( ) : (
<motion.div <motion.div
key="completed" key="completed"
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
transition={{ duration: 0.3 }} transition={{ duration: 0.3 }}
> >
<Accordion type="single" collapsible> <Accordion type="single" collapsible>
<AccordionItem value="steps" className="border-none"> <AccordionItem value="steps" className="border-none">
<AccordionTrigger className="hover:no-underline p-0 py-2"> <AccordionTrigger className="hover:no-underline p-0 py-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-mmd font-medium text-muted-foreground"> <span className="text-mmd font-medium text-muted-foreground">
{`Initialized in ${(elapsedTime / 1000).toFixed(1)} seconds`} {`Initialized in ${(elapsedTime / 1000).toFixed(1)} seconds`}
</span> </span>
</div> </div>
</AccordionTrigger> </AccordionTrigger>
<AccordionContent className="pl-0 pt-2 pb-0"> <AccordionContent className="pl-0 pt-2 pb-0">
<div className="relative pl-1"> <div className="relative pl-1">
{/* Connecting line on the left */} {/* Connecting line on the left */}
<motion.div <motion.div
className="absolute left-[7px] top-0 bottom-0 w-px bg-border z-0" className="absolute left-[7px] top-0 bottom-0 w-px bg-border z-0"
initial={{ scaleY: 0 }} initial={{ scaleY: 0 }}
animate={{ scaleY: 1 }} animate={{ scaleY: 1 }}
transition={{ duration: 0.3, ease: "easeOut" }} transition={{ duration: 0.3, ease: "easeOut" }}
style={{ transformOrigin: "top" }} style={{ transformOrigin: "top" }}
/> />
<div className="space-y-3 ml-4"> <div className="space-y-3 ml-4">
<AnimatePresence> <AnimatePresence>
{steps.map((step, index) => ( {steps.map((step, index) => (
<motion.div <motion.div
key={step} key={step}
initial={{ opacity: 0, x: -10 }} initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }} animate={{ opacity: 1, x: 0 }}
transition={{ transition={{
duration: 0.3, duration: 0.3,
delay: index * 0.05, delay: index * 0.05,
}} }}
className="flex items-center gap-1.5" className="flex items-center gap-1.5"
> >
<motion.div <motion.div
className="relative w-3.5 h-3.5 shrink-0 z-10 bg-background" className="relative w-3.5 h-3.5 shrink-0 z-10 bg-background"
initial={{ scale: 0 }} initial={{ scale: 0 }}
animate={{ scale: 1 }} animate={{ scale: 1 }}
transition={{ transition={{
duration: 0.2, duration: 0.2,
delay: index * 0.05 + 0.1, delay: index * 0.05 + 0.1,
}} }}
> >
<motion.div <motion.div
key="check" key="check"
initial={{ scale: 0, rotate: -180 }} initial={{ scale: 0, rotate: -180 }}
animate={{ scale: 1, rotate: 0 }} animate={{ scale: 1, rotate: 0 }}
transition={{ duration: 0.3 }} transition={{ duration: 0.3 }}
> >
<CheckIcon className="text-accent-emerald-foreground w-3.5 h-3.5" /> <CheckIcon className="text-accent-emerald-foreground w-3.5 h-3.5" />
</motion.div> </motion.div>
</motion.div> </motion.div>
<span className="text-mmd text-muted-foreground"> <span className="text-mmd text-muted-foreground">
{step} {step}
</span> </span>
</motion.div> </motion.div>
))} ))}
</AnimatePresence> </AnimatePresence>
</div> </div>
</div> </div>
</AccordionContent> </AccordionContent>
</AccordionItem> </AccordionItem>
</Accordion> </Accordion>
</motion.div> </motion.div>
)} )}
</AnimatePresence> </AnimatePresence>
); );
} }

View file

@ -6,8 +6,8 @@ import { Info, X } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { import {
type OnboardingVariables, type OnboardingVariables,
useOnboardingMutation, useOnboardingMutation,
} from "@/app/api/mutations/useOnboardingMutation"; } from "@/app/api/mutations/useOnboardingMutation";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery"; import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery"; import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
@ -20,10 +20,11 @@ import OpenAILogo from "@/components/icons/openai-logo";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { import {
Tooltip, Tooltip,
TooltipContent, TooltipContent,
TooltipTrigger, TooltipTrigger,
} from "@/components/ui/tooltip"; } from "@/components/ui/tooltip";
import { ONBOARDING_CARD_STEPS_KEY } from "@/lib/constants";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { AnimatedProviderSteps } from "./animated-provider-steps"; import { AnimatedProviderSteps } from "./animated-provider-steps";
import { AnthropicOnboarding } from "./anthropic-onboarding"; import { AnthropicOnboarding } from "./anthropic-onboarding";
@ -33,506 +34,507 @@ import { OpenAIOnboarding } from "./openai-onboarding";
import { TabTrigger } from "./tab-trigger"; import { TabTrigger } from "./tab-trigger";
interface OnboardingCardProps { interface OnboardingCardProps {
onComplete: () => void; onComplete: () => void;
isCompleted?: boolean; isCompleted?: boolean;
isEmbedding?: boolean; isEmbedding?: boolean;
setIsLoadingModels?: (isLoading: boolean) => void; setIsLoadingModels?: (isLoading: boolean) => void;
setLoadingStatus?: (status: string[]) => void; setLoadingStatus?: (status: string[]) => void;
} }
const STEP_LIST = [ const STEP_LIST = [
"Setting up your model provider", "Setting up your model provider",
"Defining schema", "Defining schema",
"Configuring Langflow", "Configuring Langflow",
]; ];
const EMBEDDING_STEP_LIST = [ const EMBEDDING_STEP_LIST = [
"Setting up your model provider", "Setting up your model provider",
"Defining schema", "Defining schema",
"Configuring Langflow", "Configuring Langflow",
"Ingesting sample data", "Ingesting sample data",
]; ];
const OnboardingCard = ({ const OnboardingCard = ({
onComplete, onComplete,
isEmbedding = false, isEmbedding = false,
isCompleted = false, isCompleted = false,
}: OnboardingCardProps) => { }: OnboardingCardProps) => {
const { isHealthy: isDoclingHealthy } = useDoclingHealth(); const { isHealthy: isDoclingHealthy } = useDoclingHealth();
const [modelProvider, setModelProvider] = useState<string>( const [modelProvider, setModelProvider] = useState<string>(
isEmbedding ? "openai" : "anthropic", 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 // Fetch current settings to check if providers are already configured
const { data: currentSettings } = useGetSettingsQuery(); const { data: currentSettings } = useGetSettingsQuery();
const handleSetModelProvider = (provider: string) => { const handleSetModelProvider = (provider: string) => {
setIsLoadingModels(false); setIsLoadingModels(false);
setModelProvider(provider); setModelProvider(provider);
setSettings({ setSettings({
[isEmbedding ? "embedding_provider" : "llm_provider"]: provider, [isEmbedding ? "embedding_provider" : "llm_provider"]: provider,
embedding_model: "", embedding_model: "",
llm_model: "", llm_model: "",
}); });
setError(null); setError(null);
}; };
// Check if the selected provider is already configured // Check if the selected provider is already configured
const isProviderAlreadyConfigured = (provider: string): boolean => { const isProviderAlreadyConfigured = (provider: string): boolean => {
if (!isEmbedding || !currentSettings?.providers) return false; if (!isEmbedding || !currentSettings?.providers) return false;
// Check if provider has been explicitly configured (not just from env vars) // Check if provider has been explicitly configured (not just from env vars)
if (provider === "openai") { if (provider === "openai") {
return currentSettings.providers.openai?.configured === true; return currentSettings.providers.openai?.configured === true;
} else if (provider === "anthropic") { } else if (provider === "anthropic") {
return currentSettings.providers.anthropic?.configured === true; return currentSettings.providers.anthropic?.configured === true;
} else if (provider === "watsonx") { } else if (provider === "watsonx") {
return currentSettings.providers.watsonx?.configured === true; return currentSettings.providers.watsonx?.configured === true;
} else if (provider === "ollama") { } else if (provider === "ollama") {
return currentSettings.providers.ollama?.configured === true; return currentSettings.providers.ollama?.configured === true;
} }
return false; return false;
}; };
const showProviderConfiguredMessage = const showProviderConfiguredMessage =
isProviderAlreadyConfigured(modelProvider); isProviderAlreadyConfigured(modelProvider);
const providerAlreadyConfigured = const providerAlreadyConfigured =
isEmbedding && showProviderConfiguredMessage; isEmbedding && showProviderConfiguredMessage;
const totalSteps = isEmbedding const totalSteps = isEmbedding
? EMBEDDING_STEP_LIST.length ? EMBEDDING_STEP_LIST.length
: STEP_LIST.length; : STEP_LIST.length;
const [settings, setSettings] = useState<OnboardingVariables>({ const [settings, setSettings] = useState<OnboardingVariables>({
[isEmbedding ? "embedding_provider" : "llm_provider"]: modelProvider, [isEmbedding ? "embedding_provider" : "llm_provider"]: modelProvider,
embedding_model: "", embedding_model: "",
llm_model: "", llm_model: "",
// Provider-specific fields will be set by provider components // Provider-specific fields will be set by provider components
openai_api_key: "", openai_api_key: "",
anthropic_api_key: "", anthropic_api_key: "",
watsonx_api_key: "", watsonx_api_key: "",
watsonx_endpoint: "", watsonx_endpoint: "",
watsonx_project_id: "", watsonx_project_id: "",
ollama_endpoint: "", ollama_endpoint: "",
}); });
const [currentStep, setCurrentStep] = useState<number | null>( const [currentStep, setCurrentStep] = useState<number | null>(
isCompleted ? totalSteps : null, isCompleted ? totalSteps : null,
); );
const [processingStartTime, setProcessingStartTime] = useState<number | null>( const [processingStartTime, setProcessingStartTime] = useState<number | null>(
null, null,
); );
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// Query tasks to track completion // Query tasks to track completion
const { data: tasks } = useGetTasksQuery({ const { data: tasks } = useGetTasksQuery({
enabled: currentStep !== null, // Only poll when onboarding has started enabled: currentStep !== null, // Only poll when onboarding has started
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during onboarding refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during onboarding
}); });
// Monitor tasks and call onComplete when all tasks are done // Monitor tasks and call onComplete when all tasks are done
useEffect(() => { useEffect(() => {
if (currentStep === null || !tasks || !isEmbedding) { if (currentStep === null || !tasks || !isEmbedding) {
return; return;
} }
// Check if there are any active tasks (pending, running, or processing) // Check if there are any active tasks (pending, running, or processing)
const activeTasks = tasks.find( const activeTasks = tasks.find(
(task) => (task) =>
task.status === "pending" || task.status === "pending" ||
task.status === "running" || task.status === "running" ||
task.status === "processing", task.status === "processing",
); );
// If no active tasks and we've started onboarding, complete it // If no active tasks and we've started onboarding, complete it
if ( if (
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) && (!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
tasks.length > 0 && tasks.length > 0 &&
!isCompleted !isCompleted
) { ) {
// Set to final step to show "Done" // Set to final step to show "Done"
setCurrentStep(totalSteps); setCurrentStep(totalSteps);
// Wait a bit before completing // Wait a bit before completing
setTimeout(() => { setTimeout(() => {
onComplete(); onComplete();
}, 1000); }, 1000);
} }
}, [tasks, currentStep, onComplete, isCompleted, isEmbedding, totalSteps]); }, [tasks, currentStep, onComplete, isCompleted, isEmbedding, totalSteps]);
// Mutations // Mutations
const onboardingMutation = useOnboardingMutation({ const onboardingMutation = useOnboardingMutation({
onSuccess: (data) => { onSuccess: (data) => {
console.log("Onboarding completed successfully", data); console.log("Onboarding completed successfully", data);
// Update provider health cache to healthy since backend just validated // Update provider health cache to healthy since backend just validated
const provider = const provider =
(isEmbedding ? settings.embedding_provider : settings.llm_provider) || (isEmbedding ? settings.embedding_provider : settings.llm_provider) ||
modelProvider; modelProvider;
const healthData: ProviderHealthResponse = { const healthData: ProviderHealthResponse = {
status: "healthy", status: "healthy",
message: "Provider is configured and working correctly", message: "Provider is configured and working correctly",
provider: provider, provider: provider,
}; };
queryClient.setQueryData(["provider", "health"], healthData); queryClient.setQueryData(["provider", "health"], healthData);
setError(null); setError(null);
if (!isEmbedding) { if (!isEmbedding) {
setCurrentStep(totalSteps); setCurrentStep(totalSteps);
setTimeout(() => { setTimeout(() => {
onComplete(); onComplete();
}, 1000); }, 1000);
} else { } else {
setCurrentStep(0); setCurrentStep(0);
} }
}, },
onError: (error) => { onError: (error) => {
setError(error.message); setError(error.message);
setCurrentStep(totalSteps); setCurrentStep(totalSteps);
// Reset to provider selection after 1 second // Reset to provider selection after 1 second
setTimeout(() => { setTimeout(() => {
setCurrentStep(null); setCurrentStep(null);
}, 1000); }, 1000);
}, },
}); });
const handleComplete = () => { const handleComplete = () => {
const currentProvider = isEmbedding const currentProvider = isEmbedding
? settings.embedding_provider ? settings.embedding_provider
: settings.llm_provider; : settings.llm_provider;
if ( if (
!currentProvider || !currentProvider ||
(isEmbedding && (isEmbedding &&
!settings.embedding_model && !settings.embedding_model &&
!showProviderConfiguredMessage) || !showProviderConfiguredMessage) ||
(!isEmbedding && !settings.llm_model) (!isEmbedding && !settings.llm_model)
) { ) {
toast.error("Please complete all required fields"); toast.error("Please complete all required fields");
return; return;
} }
// Clear any previous error // Clear any previous error
setError(null); setError(null);
// Prepare onboarding data with provider-specific fields // Prepare onboarding data with provider-specific fields
const onboardingData: OnboardingVariables = { const onboardingData: OnboardingVariables = {
sample_data: sampleDataset, sample_data: sampleDataset,
}; };
// Set the provider field // Set the provider field
if (isEmbedding) { if (isEmbedding) {
onboardingData.embedding_provider = currentProvider; onboardingData.embedding_provider = currentProvider;
// If provider is already configured, use the existing embedding model from settings // If provider is already configured, use the existing embedding model from settings
// Otherwise, use the embedding model from the form // Otherwise, use the embedding model from the form
if ( if (
showProviderConfiguredMessage && showProviderConfiguredMessage &&
currentSettings?.knowledge?.embedding_model currentSettings?.knowledge?.embedding_model
) { ) {
onboardingData.embedding_model = onboardingData.embedding_model =
currentSettings.knowledge.embedding_model; currentSettings.knowledge.embedding_model;
} else { } else {
onboardingData.embedding_model = settings.embedding_model; onboardingData.embedding_model = settings.embedding_model;
} }
} else { } else {
onboardingData.llm_provider = currentProvider; onboardingData.llm_provider = currentProvider;
onboardingData.llm_model = settings.llm_model; onboardingData.llm_model = settings.llm_model;
} }
// Add provider-specific credentials based on the selected provider // Add provider-specific credentials based on the selected provider
if (currentProvider === "openai" && settings.openai_api_key) { if (currentProvider === "openai" && settings.openai_api_key) {
onboardingData.openai_api_key = settings.openai_api_key; onboardingData.openai_api_key = settings.openai_api_key;
} else if (currentProvider === "anthropic" && settings.anthropic_api_key) { } else if (currentProvider === "anthropic" && settings.anthropic_api_key) {
onboardingData.anthropic_api_key = settings.anthropic_api_key; onboardingData.anthropic_api_key = settings.anthropic_api_key;
} else if (currentProvider === "watsonx") { } else if (currentProvider === "watsonx") {
if (settings.watsonx_api_key) { if (settings.watsonx_api_key) {
onboardingData.watsonx_api_key = settings.watsonx_api_key; onboardingData.watsonx_api_key = settings.watsonx_api_key;
} }
if (settings.watsonx_endpoint) { if (settings.watsonx_endpoint) {
onboardingData.watsonx_endpoint = settings.watsonx_endpoint; onboardingData.watsonx_endpoint = settings.watsonx_endpoint;
} }
if (settings.watsonx_project_id) { if (settings.watsonx_project_id) {
onboardingData.watsonx_project_id = settings.watsonx_project_id; onboardingData.watsonx_project_id = settings.watsonx_project_id;
} }
} else if (currentProvider === "ollama" && settings.ollama_endpoint) { } else if (currentProvider === "ollama" && settings.ollama_endpoint) {
onboardingData.ollama_endpoint = settings.ollama_endpoint; onboardingData.ollama_endpoint = settings.ollama_endpoint;
} }
// Record the start time when user clicks Complete // Record the start time when user clicks Complete
setProcessingStartTime(Date.now()); setProcessingStartTime(Date.now());
onboardingMutation.mutate(onboardingData); onboardingMutation.mutate(onboardingData);
setCurrentStep(0); setCurrentStep(0);
}; };
const isComplete = const isComplete =
(isEmbedding && (isEmbedding &&
(!!settings.embedding_model || showProviderConfiguredMessage)) || (!!settings.embedding_model || showProviderConfiguredMessage)) ||
(!isEmbedding && !!settings.llm_model && isDoclingHealthy); (!isEmbedding && !!settings.llm_model && isDoclingHealthy);
return ( return (
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{currentStep === null ? ( {currentStep === null ? (
<motion.div <motion.div
key="onboarding-form" key="onboarding-form"
initial={{ opacity: 0, y: -24 }} initial={{ opacity: 0, y: -24 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 24 }} exit={{ opacity: 0, y: 24 }}
transition={{ duration: 0.4, ease: "easeInOut" }} transition={{ duration: 0.4, ease: "easeInOut" }}
> >
<div className={`w-full max-w-[600px] flex flex-col`}> <div className={`w-full max-w-[600px] flex flex-col`}>
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{error && ( {error && (
<motion.div <motion.div
key="error" key="error"
initial={{ opacity: 1, y: 0, height: "auto" }} initial={{ opacity: 1, y: 0, height: "auto" }}
exit={{ opacity: 0, y: -10, height: 0 }} exit={{ opacity: 0, y: -10, height: 0 }}
> >
<div className="pb-6 flex items-center gap-4"> <div className="pb-6 flex items-center gap-4">
<X className="w-4 h-4 text-destructive shrink-0" /> <X className="w-4 h-4 text-destructive shrink-0" />
<span className="text-mmd text-muted-foreground"> <span className="text-mmd text-muted-foreground">
{error} {error}
</span> </span>
</div> </div>
</motion.div> </motion.div>
)} )}
</AnimatePresence> </AnimatePresence>
<div className={`w-full flex flex-col gap-6`}> <div className={`w-full flex flex-col gap-6`}>
<Tabs <Tabs
defaultValue={modelProvider} defaultValue={modelProvider}
onValueChange={handleSetModelProvider} onValueChange={handleSetModelProvider}
> >
<TabsList className="mb-4"> <TabsList className="mb-4">
{!isEmbedding && ( {!isEmbedding && (
<TabsTrigger <TabsTrigger
value="anthropic" value="anthropic"
className={cn( className={cn(
error && error &&
modelProvider === "anthropic" && modelProvider === "anthropic" &&
"data-[state=active]:border-destructive", "data-[state=active]:border-destructive",
)} )}
> >
<TabTrigger <TabTrigger
selected={modelProvider === "anthropic"} selected={modelProvider === "anthropic"}
isLoading={isLoadingModels} isLoading={isLoadingModels}
> >
<div <div
className={cn( className={cn(
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border", "flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
modelProvider === "anthropic" modelProvider === "anthropic"
? "bg-[#D97757]" ? "bg-[#D97757]"
: "bg-muted", : "bg-muted",
)} )}
> >
<AnthropicLogo <AnthropicLogo
className={cn( className={cn(
"w-4 h-4 shrink-0", "w-4 h-4 shrink-0",
modelProvider === "anthropic" modelProvider === "anthropic"
? "text-black" ? "text-black"
: "text-muted-foreground", : "text-muted-foreground",
)} )}
/> />
</div> </div>
Anthropic Anthropic
</TabTrigger> </TabTrigger>
</TabsTrigger> </TabsTrigger>
)} )}
<TabsTrigger <TabsTrigger
value="openai" value="openai"
className={cn( className={cn(
error && error &&
modelProvider === "openai" && modelProvider === "openai" &&
"data-[state=active]:border-destructive", "data-[state=active]:border-destructive",
)} )}
> >
<TabTrigger <TabTrigger
selected={modelProvider === "openai"} selected={modelProvider === "openai"}
isLoading={isLoadingModels} isLoading={isLoadingModels}
> >
<div <div
className={cn( className={cn(
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border", "flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
modelProvider === "openai" ? "bg-white" : "bg-muted", modelProvider === "openai" ? "bg-white" : "bg-muted",
)} )}
> >
<OpenAILogo <OpenAILogo
className={cn( className={cn(
"w-4 h-4 shrink-0", "w-4 h-4 shrink-0",
modelProvider === "openai" modelProvider === "openai"
? "text-black" ? "text-black"
: "text-muted-foreground", : "text-muted-foreground",
)} )}
/> />
</div> </div>
OpenAI OpenAI
</TabTrigger> </TabTrigger>
</TabsTrigger> </TabsTrigger>
<TabsTrigger <TabsTrigger
value="watsonx" value="watsonx"
className={cn( className={cn(
error && error &&
modelProvider === "watsonx" && modelProvider === "watsonx" &&
"data-[state=active]:border-destructive", "data-[state=active]:border-destructive",
)} )}
> >
<TabTrigger <TabTrigger
selected={modelProvider === "watsonx"} selected={modelProvider === "watsonx"}
isLoading={isLoadingModels} isLoading={isLoadingModels}
> >
<div <div
className={cn( className={cn(
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border", "flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
modelProvider === "watsonx" modelProvider === "watsonx"
? "bg-[#1063FE]" ? "bg-[#1063FE]"
: "bg-muted", : "bg-muted",
)} )}
> >
<IBMLogo <IBMLogo
className={cn( className={cn(
"w-4 h-4 shrink-0", "w-4 h-4 shrink-0",
modelProvider === "watsonx" modelProvider === "watsonx"
? "text-white" ? "text-white"
: "text-muted-foreground", : "text-muted-foreground",
)} )}
/> />
</div> </div>
IBM watsonx.ai IBM watsonx.ai
</TabTrigger> </TabTrigger>
</TabsTrigger> </TabsTrigger>
<TabsTrigger <TabsTrigger
value="ollama" value="ollama"
className={cn( className={cn(
error && error &&
modelProvider === "ollama" && modelProvider === "ollama" &&
"data-[state=active]:border-destructive", "data-[state=active]:border-destructive",
)} )}
> >
<TabTrigger <TabTrigger
selected={modelProvider === "ollama"} selected={modelProvider === "ollama"}
isLoading={isLoadingModels} isLoading={isLoadingModels}
> >
<div <div
className={cn( className={cn(
"flex items-center justify-center gap-2 w-8 h-8 rounded-md border", "flex items-center justify-center gap-2 w-8 h-8 rounded-md border",
modelProvider === "ollama" ? "bg-white" : "bg-muted", modelProvider === "ollama" ? "bg-white" : "bg-muted",
)} )}
> >
<OllamaLogo <OllamaLogo
className={cn( className={cn(
"w-4 h-4 shrink-0", "w-4 h-4 shrink-0",
modelProvider === "ollama" modelProvider === "ollama"
? "text-black" ? "text-black"
: "text-muted-foreground", : "text-muted-foreground",
)} )}
/> />
</div> </div>
Ollama Ollama
</TabTrigger> </TabTrigger>
</TabsTrigger> </TabsTrigger>
</TabsList> </TabsList>
{!isEmbedding && ( {!isEmbedding && (
<TabsContent value="anthropic"> <TabsContent value="anthropic">
<AnthropicOnboarding <AnthropicOnboarding
setSettings={setSettings} setSettings={setSettings}
sampleDataset={sampleDataset} sampleDataset={sampleDataset}
setSampleDataset={setSampleDataset} setSampleDataset={setSampleDataset}
setIsLoadingModels={setIsLoadingModels} setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding} isEmbedding={isEmbedding}
hasEnvApiKey={ hasEnvApiKey={
currentSettings?.providers?.anthropic?.has_api_key === currentSettings?.providers?.anthropic?.has_api_key ===
true true
} }
/> />
</TabsContent> </TabsContent>
)} )}
<TabsContent value="openai"> <TabsContent value="openai">
<OpenAIOnboarding <OpenAIOnboarding
setSettings={setSettings} setSettings={setSettings}
sampleDataset={sampleDataset} sampleDataset={sampleDataset}
setSampleDataset={setSampleDataset} setSampleDataset={setSampleDataset}
setIsLoadingModels={setIsLoadingModels} setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding} isEmbedding={isEmbedding}
hasEnvApiKey={ hasEnvApiKey={
currentSettings?.providers?.openai?.has_api_key === true currentSettings?.providers?.openai?.has_api_key === true
} }
alreadyConfigured={providerAlreadyConfigured} alreadyConfigured={providerAlreadyConfigured}
/> />
</TabsContent> </TabsContent>
<TabsContent value="watsonx"> <TabsContent value="watsonx">
<IBMOnboarding <IBMOnboarding
setSettings={setSettings} setSettings={setSettings}
sampleDataset={sampleDataset} sampleDataset={sampleDataset}
setSampleDataset={setSampleDataset} setSampleDataset={setSampleDataset}
setIsLoadingModels={setIsLoadingModels} setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding} isEmbedding={isEmbedding}
alreadyConfigured={providerAlreadyConfigured} alreadyConfigured={providerAlreadyConfigured}
/> />
</TabsContent> </TabsContent>
<TabsContent value="ollama"> <TabsContent value="ollama">
<OllamaOnboarding <OllamaOnboarding
setSettings={setSettings} setSettings={setSettings}
sampleDataset={sampleDataset} sampleDataset={sampleDataset}
setSampleDataset={setSampleDataset} setSampleDataset={setSampleDataset}
setIsLoadingModels={setIsLoadingModels} setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding} isEmbedding={isEmbedding}
alreadyConfigured={providerAlreadyConfigured} alreadyConfigured={providerAlreadyConfigured}
/> />
</TabsContent> </TabsContent>
</Tabs> </Tabs>
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<div> <div>
<Button <Button
size="sm" size="sm"
onClick={handleComplete} onClick={handleComplete}
disabled={!isComplete || isLoadingModels} disabled={!isComplete || isLoadingModels}
loading={onboardingMutation.isPending} loading={onboardingMutation.isPending}
> >
<span className="select-none">Complete</span> <span className="select-none">Complete</span>
</Button> </Button>
</div> </div>
</TooltipTrigger> </TooltipTrigger>
{!isComplete && ( {!isComplete && (
<TooltipContent> <TooltipContent>
{isLoadingModels {isLoadingModels
? "Loading models..." ? "Loading models..."
: !!settings.llm_model && : !!settings.llm_model &&
!!settings.embedding_model && !!settings.embedding_model &&
!isDoclingHealthy !isDoclingHealthy
? "docling-serve must be running to continue" ? "docling-serve must be running to continue"
: "Please fill in all required fields"} : "Please fill in all required fields"}
</TooltipContent> </TooltipContent>
)} )}
</Tooltip> </Tooltip>
</div> </div>
</div> </div>
</motion.div> </motion.div>
) : ( ) : (
<motion.div <motion.div
key="provider-steps" key="provider-steps"
initial={{ opacity: 0, y: 24 }} initial={{ opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 24 }} exit={{ opacity: 0, y: 24 }}
transition={{ duration: 0.4, ease: "easeInOut" }} transition={{ duration: 0.4, ease: "easeInOut" }}
> >
<AnimatedProviderSteps <AnimatedProviderSteps
currentStep={currentStep} currentStep={currentStep}
isCompleted={isCompleted} isCompleted={isCompleted}
setCurrentStep={setCurrentStep} setCurrentStep={setCurrentStep}
steps={isEmbedding ? EMBEDDING_STEP_LIST : STEP_LIST} steps={isEmbedding ? EMBEDDING_STEP_LIST : STEP_LIST}
processingStartTime={processingStartTime} processingStartTime={processingStartTime}
hasError={!!error} storageKey={ONBOARDING_CARD_STEPS_KEY}
/> hasError={!!error}
</motion.div> />
)} </motion.div>
</AnimatePresence> )}
); </AnimatePresence>
);
}; };
export default OnboardingCard; export default OnboardingCard;

View file

@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { StickToBottom } from "use-stick-to-bottom"; import { StickToBottom } from "use-stick-to-bottom";
import { AssistantMessage } from "@/app/chat/_components/assistant-message"; import { AssistantMessage } from "@/app/chat/_components/assistant-message";
import Nudges from "@/app/chat/_components/nudges"; import Nudges from "@/app/chat/_components/nudges";
@ -8,26 +8,79 @@ import { UserMessage } from "@/app/chat/_components/user-message";
import type { Message } from "@/app/chat/_types/types"; import type { Message } from "@/app/chat/_types/types";
import OnboardingCard from "@/app/onboarding/_components/onboarding-card"; import OnboardingCard from "@/app/onboarding/_components/onboarding-card";
import { useChatStreaming } from "@/hooks/useChatStreaming"; import { useChatStreaming } from "@/hooks/useChatStreaming";
import {
ONBOARDING_ASSISTANT_MESSAGE_KEY,
ONBOARDING_SELECTED_NUDGE_KEY,
} from "@/lib/constants";
import { OnboardingStep } from "./onboarding-step"; import { OnboardingStep } from "./onboarding-step";
import OnboardingUpload from "./onboarding-upload"; import OnboardingUpload from "./onboarding-upload";
export function OnboardingContent({ export function OnboardingContent({
handleStepComplete, handleStepComplete,
handleStepBack,
currentStep, currentStep,
}: { }: {
handleStepComplete: () => void; handleStepComplete: () => void;
handleStepBack: () => void;
currentStep: number; currentStep: number;
}) { }) {
const parseFailedRef = useRef(false);
const [responseId, setResponseId] = useState<string | null>(null); const [responseId, setResponseId] = useState<string | null>(null);
const [selectedNudge, setSelectedNudge] = useState<string>(""); const [selectedNudge, setSelectedNudge] = useState<string>(() => {
// Retrieve selected nudge from localStorage on mount
if (typeof window === "undefined") return "";
return localStorage.getItem(ONBOARDING_SELECTED_NUDGE_KEY) || "";
});
const [assistantMessage, setAssistantMessage] = useState<Message | null>( const [assistantMessage, setAssistantMessage] = useState<Message | null>(
null, () => {
// Retrieve assistant message from localStorage on mount
if (typeof window === "undefined") return null;
const savedMessage = localStorage.getItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
if (savedMessage) {
try {
const parsed = JSON.parse(savedMessage);
// Convert timestamp string back to Date object
return {
...parsed,
timestamp: new Date(parsed.timestamp),
};
} catch (error) {
console.error("Failed to parse saved assistant message:", error);
parseFailedRef.current = true;
// Clear corrupted data - will go back a step in useEffect
if (typeof window !== "undefined") {
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
}
return null;
}
}
return null;
},
); );
// Handle parse errors by going back a step
useEffect(() => {
if (parseFailedRef.current && currentStep >= 2) {
handleStepBack();
}
}, [handleStepBack, currentStep]);
const { streamingMessage, isLoading, sendMessage } = useChatStreaming({ const { streamingMessage, isLoading, sendMessage } = useChatStreaming({
onComplete: (message, newResponseId) => { onComplete: (message, newResponseId) => {
setAssistantMessage(message); setAssistantMessage(message);
// Save assistant message to localStorage when complete
if (typeof window !== "undefined") {
try {
localStorage.setItem(
ONBOARDING_ASSISTANT_MESSAGE_KEY,
JSON.stringify(message),
);
} catch (error) {
console.error("Failed to save assistant message to localStorage:", error);
}
}
if (newResponseId) { if (newResponseId) {
setResponseId(newResponseId); setResponseId(newResponseId);
} }
@ -47,7 +100,15 @@ export function OnboardingContent({
const handleNudgeClick = async (nudge: string) => { const handleNudgeClick = async (nudge: string) => {
setSelectedNudge(nudge); setSelectedNudge(nudge);
// Save selected nudge to localStorage
if (typeof window !== "undefined") {
localStorage.setItem(ONBOARDING_SELECTED_NUDGE_KEY, nudge);
}
setAssistantMessage(null); setAssistantMessage(null);
// Clear saved assistant message when starting a new conversation
if (typeof window !== "undefined") {
localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
}
setTimeout(async () => { setTimeout(async () => {
await sendMessage({ await sendMessage({
prompt: nudge, prompt: nudge,

View file

@ -4,154 +4,156 @@ import { useGetNudgesQuery } from "@/app/api/queries/useGetNudgesQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery"; import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
import { AnimatedProviderSteps } from "@/app/onboarding/_components/animated-provider-steps"; import { AnimatedProviderSteps } from "@/app/onboarding/_components/animated-provider-steps";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ONBOARDING_UPLOAD_STEPS_KEY } from "@/lib/constants";
import { uploadFile } from "@/lib/upload-utils"; import { uploadFile } from "@/lib/upload-utils";
interface OnboardingUploadProps { interface OnboardingUploadProps {
onComplete: () => void; onComplete: () => void;
} }
const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => { const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
const [currentStep, setCurrentStep] = useState<number | null>(null); const [currentStep, setCurrentStep] = useState<number | null>(null);
const STEP_LIST = [ const STEP_LIST = [
"Uploading your document", "Uploading your document",
"Generating embeddings", "Generating embeddings",
"Ingesting document", "Ingesting document",
"Processing your document", "Processing your document",
]; ];
// Query tasks to track completion // Query tasks to track completion
const { data: tasks } = useGetTasksQuery({ const { data: tasks } = useGetTasksQuery({
enabled: currentStep !== null, // Only poll when upload has started enabled: currentStep !== null, // Only poll when upload has started
refetchInterval: currentStep !== null ? 1000 : false, // Poll every 1 second during upload 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 // Monitor tasks and call onComplete when file processing is done
useEffect(() => { useEffect(() => {
if (currentStep === null || !tasks) { if (currentStep === null || !tasks) {
return; return;
} }
// Check if there are any active tasks (pending, running, or processing) // Check if there are any active tasks (pending, running, or processing)
const activeTasks = tasks.find( const activeTasks = tasks.find(
(task) => (task) =>
task.status === "pending" || task.status === "pending" ||
task.status === "running" || task.status === "running" ||
task.status === "processing", task.status === "processing",
); );
// If no active tasks and we have more than 1 task (initial + new upload), complete it // If no active tasks and we have more than 1 task (initial + new upload), complete it
if ( if (
(!activeTasks || (activeTasks.processed_files ?? 0) > 0) && (!activeTasks || (activeTasks.processed_files ?? 0) > 0) &&
tasks.length > 1 tasks.length > 1
) { ) {
// Set to final step to show "Done" // Set to final step to show "Done"
setCurrentStep(STEP_LIST.length); setCurrentStep(STEP_LIST.length);
// Refetch nudges to get new ones // Refetch nudges to get new ones
refetchNudges(); refetchNudges();
// Wait a bit before completing // Wait a bit before completing
setTimeout(() => { setTimeout(() => {
onComplete(); onComplete();
}, 1000); }, 1000);
} }
}, [tasks, currentStep, onComplete, refetchNudges]); }, [tasks, currentStep, onComplete, refetchNudges]);
const resetFileInput = () => { const resetFileInput = () => {
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ""; fileInputRef.current.value = "";
} }
}; };
const handleUploadClick = () => { const handleUploadClick = () => {
fileInputRef.current?.click(); fileInputRef.current?.click();
}; };
const performUpload = async (file: File) => { const performUpload = async (file: File) => {
setIsUploading(true); setIsUploading(true);
try { try {
setCurrentStep(0); setCurrentStep(0);
await uploadFile(file, true); await uploadFile(file, true);
console.log("Document upload task started successfully"); console.log("Document upload task started successfully");
// Move to processing step - task monitoring will handle completion // Move to processing step - task monitoring will handle completion
setTimeout(() => { setTimeout(() => {
setCurrentStep(1); setCurrentStep(1);
}, 1500); }, 1500);
} catch (error) { } catch (error) {
console.error("Upload failed", (error as Error).message); console.error("Upload failed", (error as Error).message);
// Reset on error // Reset on error
setCurrentStep(null); setCurrentStep(null);
} finally { } finally {
setIsUploading(false); setIsUploading(false);
} }
}; };
const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => { const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0]; const selectedFile = event.target.files?.[0];
if (!selectedFile) { if (!selectedFile) {
resetFileInput(); resetFileInput();
return; return;
} }
try { try {
await performUpload(selectedFile); await performUpload(selectedFile);
} catch (error) { } catch (error) {
console.error( console.error(
"Unable to prepare file for upload", "Unable to prepare file for upload",
(error as Error).message, (error as Error).message,
); );
} finally { } finally {
resetFileInput(); resetFileInput();
} }
}; };
return ( return (
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{currentStep === null ? ( {currentStep === null ? (
<motion.div <motion.div
key="user-ingest" key="user-ingest"
initial={{ opacity: 1, y: 0 }} initial={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -24 }} exit={{ opacity: 0, y: -24 }}
transition={{ duration: 0.4, ease: "easeInOut" }} transition={{ duration: 0.4, ease: "easeInOut" }}
> >
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
onClick={handleUploadClick} onClick={handleUploadClick}
disabled={isUploading} disabled={isUploading}
> >
<div>{isUploading ? "Uploading..." : "Add a document"}</div> <div>{isUploading ? "Uploading..." : "Add a document"}</div>
</Button> </Button>
<input <input
ref={fileInputRef} ref={fileInputRef}
type="file" type="file"
onChange={handleFileChange} onChange={handleFileChange}
className="hidden" className="hidden"
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt" accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
/> />
</motion.div> </motion.div>
) : ( ) : (
<motion.div <motion.div
key="ingest-steps" key="ingest-steps"
initial={{ opacity: 0, y: 24 }} initial={{ opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: "easeInOut" }} transition={{ duration: 0.4, ease: "easeInOut" }}
> >
<AnimatedProviderSteps <AnimatedProviderSteps
currentStep={currentStep} currentStep={currentStep}
setCurrentStep={setCurrentStep} setCurrentStep={setCurrentStep}
isCompleted={false} isCompleted={false}
steps={STEP_LIST} steps={STEP_LIST}
/> storageKey={ONBOARDING_UPLOAD_STEPS_KEY}
</motion.div> />
)} </motion.div>
</AnimatePresence> )}
); </AnimatePresence>
);
}; };
export default OnboardingUpload; export default OnboardingUpload;

View file

@ -32,7 +32,7 @@ export function ProgressBar({
</span> </span>
</div> </div>
<div className="flex-1 flex justify-end"> <div className="flex-1 flex justify-end">
{currentStep > 0 && onSkip && ( {currentStep > 1 && onSkip && (
<Button <Button
variant="link" variant="link"
size="sm" size="sm"

View file

@ -4,8 +4,8 @@ import { motion } from "framer-motion";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { import {
type ChatConversation, type ChatConversation,
useGetConversationsQuery, useGetConversationsQuery,
} from "@/app/api/queries/useGetConversationsQuery"; } from "@/app/api/queries/useGetConversationsQuery";
import type { Settings } from "@/app/api/queries/useGetSettingsQuery"; import type { Settings } from "@/app/api/queries/useGetSettingsQuery";
import { OnboardingContent } from "@/app/onboarding/_components/onboarding-content"; import { OnboardingContent } from "@/app/onboarding/_components/onboarding-content";
@ -16,200 +16,223 @@ import { Navigation } from "@/components/navigation";
import { useAuth } from "@/contexts/auth-context"; import { useAuth } from "@/contexts/auth-context";
import { useChat } from "@/contexts/chat-context"; import { useChat } from "@/contexts/chat-context";
import { import {
ANIMATION_DURATION, ANIMATION_DURATION,
HEADER_HEIGHT, HEADER_HEIGHT,
ONBOARDING_STEP_KEY, ONBOARDING_ASSISTANT_MESSAGE_KEY,
SIDEBAR_WIDTH, ONBOARDING_CARD_STEPS_KEY,
TOTAL_ONBOARDING_STEPS, ONBOARDING_SELECTED_NUDGE_KEY,
ONBOARDING_STEP_KEY,
ONBOARDING_UPLOAD_STEPS_KEY,
SIDEBAR_WIDTH,
TOTAL_ONBOARDING_STEPS,
} from "@/lib/constants"; } from "@/lib/constants";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export function ChatRenderer({ export function ChatRenderer({
settings, settings,
children, children,
}: { }: {
settings: Settings | undefined; settings: Settings | undefined;
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const pathname = usePathname(); const pathname = usePathname();
const { isAuthenticated, isNoAuthMode } = useAuth(); const { isAuthenticated, isNoAuthMode } = useAuth();
const { const {
endpoint, endpoint,
refreshTrigger, refreshTrigger,
refreshConversations, refreshConversations,
startNewConversation, startNewConversation,
} = useChat(); } = useChat();
// Initialize onboarding state based on local storage and settings // Initialize onboarding state based on local storage and settings
const [currentStep, setCurrentStep] = useState<number>(() => { const [currentStep, setCurrentStep] = useState<number>(() => {
if (typeof window === "undefined") return 0; if (typeof window === "undefined") return 0;
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY); const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
return savedStep !== null ? parseInt(savedStep, 10) : 0; return savedStep !== null ? parseInt(savedStep, 10) : 0;
}); });
const [showLayout, setShowLayout] = useState<boolean>(() => { const [showLayout, setShowLayout] = useState<boolean>(() => {
if (typeof window === "undefined") return false; if (typeof window === "undefined") return false;
const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY); const savedStep = localStorage.getItem(ONBOARDING_STEP_KEY);
// Show layout if settings.edited is true and if no onboarding step is saved // Show layout if settings.edited is true and if no onboarding step is saved
const isEdited = settings?.edited ?? true; const isEdited = settings?.edited ?? true;
return isEdited ? savedStep === null : false; return isEdited ? savedStep === null : false;
}); });
// Only fetch conversations on chat page // Only fetch conversations on chat page
const isOnChatPage = pathname === "/" || pathname === "/chat"; const isOnChatPage = pathname === "/" || pathname === "/chat";
const { data: conversations = [], isLoading: isConversationsLoading } = const { data: conversations = [], isLoading: isConversationsLoading } =
useGetConversationsQuery(endpoint, refreshTrigger, { useGetConversationsQuery(endpoint, refreshTrigger, {
enabled: isOnChatPage && (isAuthenticated || isNoAuthMode), enabled: isOnChatPage && (isAuthenticated || isNoAuthMode),
}) as { data: ChatConversation[]; isLoading: boolean }; }) as { data: ChatConversation[]; isLoading: boolean };
const handleNewConversation = () => { const handleNewConversation = () => {
refreshConversations(); refreshConversations();
startNewConversation(); startNewConversation();
}; };
// Save current step to local storage whenever it changes // Save current step to local storage whenever it changes
useEffect(() => { useEffect(() => {
if (typeof window !== "undefined" && !showLayout) { if (typeof window !== "undefined" && !showLayout) {
localStorage.setItem(ONBOARDING_STEP_KEY, currentStep.toString()); localStorage.setItem(ONBOARDING_STEP_KEY, currentStep.toString());
} }
}, [currentStep, showLayout]); }, [currentStep, showLayout]);
const handleStepComplete = () => { const handleStepComplete = () => {
if (currentStep < TOTAL_ONBOARDING_STEPS - 1) { if (currentStep < TOTAL_ONBOARDING_STEPS - 1) {
setCurrentStep(currentStep + 1); setCurrentStep(currentStep + 1);
} else { } else {
// Onboarding is complete - remove from local storage and show layout // Onboarding is complete - remove from local storage and show layout
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
localStorage.removeItem(ONBOARDING_STEP_KEY); localStorage.removeItem(ONBOARDING_STEP_KEY);
} localStorage.removeItem(ONBOARDING_ASSISTANT_MESSAGE_KEY);
setShowLayout(true); localStorage.removeItem(ONBOARDING_SELECTED_NUDGE_KEY);
} localStorage.removeItem(ONBOARDING_CARD_STEPS_KEY);
}; localStorage.removeItem(ONBOARDING_UPLOAD_STEPS_KEY);
}
setShowLayout(true);
}
};
const handleSkipOnboarding = () => { const handleStepBack = () => {
// Skip onboarding by marking it as complete if (currentStep > 0) {
if (typeof window !== "undefined") { setCurrentStep(currentStep - 1);
localStorage.removeItem(ONBOARDING_STEP_KEY); }
} };
setShowLayout(true);
};
// List of paths with smaller max-width const handleSkipOnboarding = () => {
const smallWidthPaths = ["/settings", "/upload"]; // Skip onboarding by marking it as complete
const isSmallWidthPath = smallWidthPaths.some((path) => if (typeof window !== "undefined") {
pathname.startsWith(path), 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 x = showLayout ? "0px" : `calc(-${SIDEBAR_WIDTH / 2}px + 50vw)`; // List of paths with smaller max-width
const y = showLayout ? "0px" : `calc(-${HEADER_HEIGHT / 2}px + 50vh)`; const smallWidthPaths = ["/settings", "/upload"];
const translateY = showLayout ? "0px" : `-50vh`; const isSmallWidthPath = smallWidthPaths.some((path) =>
const translateX = showLayout ? "0px" : `-50vw`; pathname.startsWith(path),
);
// For all other pages, render with Langflow-styled navigation and task menu const x = showLayout ? "0px" : `calc(-${SIDEBAR_WIDTH / 2}px + 50vw)`;
return ( const y = showLayout ? "0px" : `calc(-${HEADER_HEIGHT / 2}px + 50vh)`;
<> const translateY = showLayout ? "0px" : `-50vh`;
<AnimatedConditional const translateX = showLayout ? "0px" : `-50vw`;
className="[grid-area:header] bg-background border-b"
vertical
slide
isOpen={showLayout}
delay={ANIMATION_DURATION / 2}
>
<Header />
</AnimatedConditional>
{/* Sidebar Navigation */} // For all other pages, render with Langflow-styled navigation and task menu
<AnimatedConditional return (
isOpen={showLayout} <>
slide <AnimatedConditional
className={`border-r bg-background overflow-hidden [grid-area:nav] w-[${SIDEBAR_WIDTH}px]`} className="[grid-area:header] bg-background border-b"
> vertical
<Navigation slide
conversations={conversations} isOpen={showLayout}
isConversationsLoading={isConversationsLoading} delay={ANIMATION_DURATION / 2}
onNewConversation={handleNewConversation} >
/> <Header />
</AnimatedConditional> </AnimatedConditional>
{/* Main Content */} {/* Sidebar Navigation */}
<main className="overflow-hidden w-full flex items-center justify-center [grid-area:main]"> <AnimatedConditional
<motion.div isOpen={showLayout}
initial={{ slide
width: showLayout ? "100%" : "100vw", className={`border-r bg-background overflow-hidden [grid-area:nav] w-[${SIDEBAR_WIDTH}px]`}
height: showLayout ? "100%" : "100vh", >
x: x, {showLayout && (
y: y, <Navigation
translateX: translateX, conversations={conversations}
translateY: translateY, isConversationsLoading={isConversationsLoading}
}} onNewConversation={handleNewConversation}
animate={{ />
width: showLayout ? "100%" : "850px", )}
borderRadius: showLayout ? "0" : "16px", </AnimatedConditional>
border: showLayout ? "0" : "1px solid hsl(var(--border))",
height: showLayout ? "100%" : "800px", {/* Main Content */}
x: x, <main className="overflow-hidden w-full flex items-center justify-center [grid-area:main]">
y: y, <motion.div
translateX: translateX, initial={{
translateY: translateY, width: showLayout ? "100%" : "100vw",
}} height: showLayout ? "100%" : "100vh",
transition={{ x: x,
duration: ANIMATION_DURATION, y: y,
ease: "easeOut", translateX: translateX,
}} translateY: translateY,
className={cn( }}
"flex h-full w-full max-w-full max-h-full items-center justify-center overflow-y-auto", animate={{
!showLayout && width: showLayout ? "100%" : "850px",
"absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]", borderRadius: showLayout ? "0" : "16px",
showLayout && !isOnChatPage && "bg-background", border: showLayout ? "0" : "1px solid hsl(var(--border))",
)} height: showLayout ? "100%" : "800px",
> x: x,
<div y: y,
className={cn( translateX: translateX,
"h-full bg-background w-full", translateY: translateY,
showLayout && !isOnChatPage && "p-6 container", }}
showLayout && isSmallWidthPath && "max-w-[850px] ml-0", transition={{
!showLayout && "p-0 py-2", duration: ANIMATION_DURATION,
)} ease: "easeOut",
> }}
<motion.div className={cn(
initial={{ "flex h-full w-full max-w-full max-h-full items-center justify-center overflow-y-auto",
opacity: showLayout ? 1 : 0, !showLayout &&
}} "absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]",
animate={{ showLayout && !isOnChatPage && "bg-background",
opacity: "100%", )}
}} >
transition={{ <div
duration: ANIMATION_DURATION, className={cn(
ease: "easeOut", "h-full bg-background w-full",
delay: ANIMATION_DURATION, showLayout && !isOnChatPage && "p-6 container",
}} showLayout && isSmallWidthPath && "max-w-[850px] ml-0",
className={cn("w-full h-full")} !showLayout && "p-0 py-2",
> )}
<div className={cn("w-full h-full", !showLayout && "hidden")}> >
{children} <motion.div
</div> initial={{
{!showLayout && ( opacity: showLayout ? 1 : 0,
<OnboardingContent }}
handleStepComplete={handleStepComplete} animate={{
currentStep={currentStep} opacity: "100%",
/> }}
)} transition={{
</motion.div> duration: ANIMATION_DURATION,
</div> ease: "easeOut",
</motion.div> delay: ANIMATION_DURATION,
<motion.div }}
initial={{ opacity: 0, y: 20 }} className={cn("w-full h-full")}
animate={{ opacity: showLayout ? 0 : 1, y: showLayout ? 20 : 0 }} >
transition={{ duration: ANIMATION_DURATION, ease: "easeOut" }} {showLayout && (
className={cn("absolute bottom-6 left-0 right-0")} <div className={cn("w-full h-full", !showLayout && "hidden")}>
> {children}
<ProgressBar </div>
currentStep={currentStep} )}
totalSteps={TOTAL_ONBOARDING_STEPS} {!showLayout && (
onSkip={handleSkipOnboarding} <OnboardingContent
/> handleStepComplete={handleStepComplete}
</motion.div> handleStepBack={handleStepBack}
</main> 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>
</>
);
} }

View file

@ -83,7 +83,6 @@ export function Navigation({
startNewConversation, startNewConversation,
conversationDocs, conversationDocs,
conversationData, conversationData,
addConversationDoc,
refreshConversations, refreshConversations,
placeholderConversation, placeholderConversation,
setPlaceholderConversation, setPlaceholderConversation,
@ -92,12 +91,12 @@ export function Navigation({
const { loading } = useLoadingStore(); const { loading } = useLoadingStore();
const [loadingNewConversation, setLoadingNewConversation] = useState(false);
const [previousConversationCount, setPreviousConversationCount] = useState(0); const [previousConversationCount, setPreviousConversationCount] = useState(0);
const [deleteModalOpen, setDeleteModalOpen] = useState(false); const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const [conversationToDelete, setConversationToDelete] = const [conversationToDelete, setConversationToDelete] =
useState<ChatConversation | null>(null); useState<ChatConversation | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null); const hasCompletedInitialLoad = useRef(false);
const mountTimeRef = useRef<number | null>(null);
const { selectedFilter, setSelectedFilter } = useKnowledgeFilter(); const { selectedFilter, setSelectedFilter } = useKnowledgeFilter();
@ -140,8 +139,6 @@ export function Navigation({
}); });
const handleNewConversation = () => { const handleNewConversation = () => {
setLoadingNewConversation(true);
// Use the prop callback if provided, otherwise use the context method // Use the prop callback if provided, otherwise use the context method
if (onNewConversation) { if (onNewConversation) {
onNewConversation(); onNewConversation();
@ -153,96 +150,8 @@ export function Navigation({
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("newConversation")); window.dispatchEvent(new CustomEvent("newConversation"));
} }
// Clear loading state after a short delay to show the new conversation is created
setTimeout(() => {
setLoadingNewConversation(false);
}, 300);
}; };
const handleFileUpload = async (file: File) => {
console.log("Navigation file upload:", file.name);
// Trigger loading start event for chat page
window.dispatchEvent(
new CustomEvent("fileUploadStart", {
detail: { filename: file.name },
}),
);
try {
const formData = new FormData();
formData.append("file", file);
formData.append("endpoint", endpoint);
const response = await fetch("/api/upload_context", {
method: "POST",
body: formData,
});
if (!response.ok) {
const errorText = await response.text();
console.error("Upload failed:", errorText);
// Trigger error event for chat page to handle
window.dispatchEvent(
new CustomEvent("fileUploadError", {
detail: {
filename: file.name,
error: "Failed to process document",
},
}),
);
// Trigger loading end event
window.dispatchEvent(new CustomEvent("fileUploadComplete"));
return;
}
const result = await response.json();
console.log("Upload result:", result);
// Add the file to conversation docs
if (result.filename) {
addConversationDoc(result.filename);
}
// Trigger file upload event for chat page to handle
window.dispatchEvent(
new CustomEvent("fileUploaded", {
detail: { file, result },
}),
);
// Trigger loading end event
window.dispatchEvent(new CustomEvent("fileUploadComplete"));
} catch (error) {
console.error("Upload failed:", error);
// Trigger loading end event even on error
window.dispatchEvent(new CustomEvent("fileUploadComplete"));
// Trigger error event for chat page to handle
window.dispatchEvent(
new CustomEvent("fileUploadError", {
detail: { filename: file.name, error: "Failed to process document" },
}),
);
}
};
const handleFilePickerClick = () => {
fileInputRef.current?.click();
};
const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
handleFileUpload(files[0]);
}
// Reset the input so the same file can be selected again
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
};
const handleDeleteConversation = ( const handleDeleteConversation = (
conversation: ChatConversation, conversation: ChatConversation,
@ -303,15 +212,43 @@ export function Navigation({
const isOnChatPage = pathname === "/" || pathname === "/chat"; const isOnChatPage = pathname === "/" || pathname === "/chat";
const isOnKnowledgePage = pathname.startsWith("/knowledge"); const isOnKnowledgePage = pathname.startsWith("/knowledge");
// Track mount time to prevent auto-selection right after component mounts (e.g., after onboarding)
useEffect(() => {
if (mountTimeRef.current === null) {
mountTimeRef.current = Date.now();
}
}, []);
// Track when initial load completes
useEffect(() => {
if (!isConversationsLoading && !hasCompletedInitialLoad.current) {
hasCompletedInitialLoad.current = true;
// Set initial count after first load completes
setPreviousConversationCount(conversations.length);
}
}, [isConversationsLoading, conversations.length]);
// Clear placeholder when conversation count increases (new conversation was created) // Clear placeholder when conversation count increases (new conversation was created)
useEffect(() => { useEffect(() => {
const currentCount = conversations.length; const currentCount = conversations.length;
const timeSinceMount = mountTimeRef.current
? Date.now() - mountTimeRef.current
: Infinity;
const MIN_TIME_AFTER_MOUNT = 2000; // 2 seconds - prevents selection right after onboarding
// If we had a placeholder and the conversation count increased, clear the placeholder and highlight the new conversation // Only select if:
// 1. We have a placeholder (new conversation was created)
// 2. Initial load has completed (prevents selection on browser refresh)
// 3. Count increased (new conversation appeared)
// 4. Not currently loading
// 5. Enough time has passed since mount (prevents selection after onboarding completes)
if ( if (
placeholderConversation && placeholderConversation &&
hasCompletedInitialLoad.current &&
currentCount > previousConversationCount && currentCount > previousConversationCount &&
conversations.length > 0 conversations.length > 0 &&
!isConversationsLoading &&
timeSinceMount >= MIN_TIME_AFTER_MOUNT
) { ) {
setPlaceholderConversation(null); setPlaceholderConversation(null);
// Highlight the most recent conversation (first in sorted array) without loading its messages // Highlight the most recent conversation (first in sorted array) without loading its messages
@ -321,8 +258,10 @@ export function Navigation({
} }
} }
// Update the previous count // Update the previous count only after initial load
setPreviousConversationCount(currentCount); if (hasCompletedInitialLoad.current) {
setPreviousConversationCount(currentCount);
}
}, [ }, [
conversations.length, conversations.length,
placeholderConversation, placeholderConversation,
@ -330,6 +269,7 @@ export function Navigation({
previousConversationCount, previousConversationCount,
conversations, conversations,
setCurrentConversationId, setCurrentConversationId,
isConversationsLoading,
]); ]);
useEffect(() => { useEffect(() => {
@ -341,10 +281,10 @@ export function Navigation({
); );
} }
if (isOnChatPage) { if (isOnChatPage && !isConversationsLoading) {
if (conversations.length === 0 && !placeholderConversation) { if (conversations.length === 0 && !placeholderConversation) {
handleNewConversation(); handleNewConversation();
} else if (activeConvo && !conversationLoaded) { } else if (activeConvo) {
loadConversation(activeConvo); loadConversation(activeConvo);
refreshConversations(); refreshConversations();
} else if ( } else if (
@ -431,35 +371,22 @@ export function Navigation({
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-hide"> <div className="flex-1 min-h-0 overflow-y-auto scrollbar-hide">
<div className="space-y-1 flex flex-col"> <div className="space-y-1 flex flex-col">
{loadingNewConversation || isConversationsLoading ? ( {/* Show skeleton loaders when loading and no conversations exist */}
<div className="text-[13px] text-muted-foreground p-2"> {isConversationsLoading && conversations.length === 0 ? (
Loading...
</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 placeholder conversation if it exists */}
{placeholderConversation && (
<button
type="button"
className="w-full px-3 rounded-lg bg-accent border border-dashed border-accent cursor-pointer group text-left h-[44px]"
onClick={() => {
// Don't load placeholder as a real conversation, just focus the input
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("focusInput"));
}
}}
>
<div className="text-[13px] font-medium text-foreground truncate">
{placeholderConversation.title}
</div>
<div className="text-xs text-muted-foreground">
Start typing to begin...
</div>
</button>
)}
{/* Show regular conversations */} {/* Show regular conversations */}
{conversations.length === 0 && !placeholderConversation ? ( {conversations.length === 0 && !isConversationsLoading ? (
<div className="text-[13px] text-muted-foreground py-2 pl-3"> <div className="text-[13px] text-muted-foreground py-2 pl-3">
No conversations yet No conversations yet
</div> </div>
@ -469,7 +396,7 @@ export function Navigation({
key={conversation.response_id} key={conversation.response_id}
type="button" type="button"
className={`w-full px-3 h-11 rounded-lg group relative text-left ${ className={`w-full px-3 h-11 rounded-lg group relative text-left ${
loading loading || isConversationsLoading
? "opacity-50 cursor-not-allowed" ? "opacity-50 cursor-not-allowed"
: "hover:bg-accent cursor-pointer" : "hover:bg-accent cursor-pointer"
} ${ } ${
@ -478,11 +405,11 @@ export function Navigation({
: "" : ""
}`} }`}
onClick={() => { onClick={() => {
if (loading) return; if (loading || isConversationsLoading) return;
loadConversation(conversation); loadConversation(conversation);
refreshConversations(); refreshConversations();
}} }}
disabled={loading} disabled={loading || isConversationsLoading}
> >
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
@ -493,7 +420,7 @@ export function Navigation({
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger <DropdownMenuTrigger
disabled={ disabled={
loading || deleteSessionMutation.isPending loading || isConversationsLoading || deleteSessionMutation.isPending
} }
asChild asChild
> >
@ -543,51 +470,6 @@ export function Navigation({
</> </>
)} )}
</div> </div>
{/* Conversation Knowledge Section - appears right after last conversation
<div className="flex-shrink-0 mt-4">
<div className="flex items-center justify-between mb-3 mx-3">
<h3 className="text-xs font-medium text-muted-foreground">
Conversation knowledge
</h3>
<button
type="button"
onClick={handleFilePickerClick}
className="p-1 hover:bg-accent rounded"
disabled={loading}
>
<Plus className="h-4 w-4 text-muted-foreground" />
</button>
</div>
<input
ref={fileInputRef}
type="file"
onChange={handleFilePickerChange}
className="hidden"
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
/>
<div className="overflow-y-auto scrollbar-hide space-y-1">
{conversationDocs.length === 0 ? (
<div className="text-[13px] text-muted-foreground py-2 px-3">
No documents yet
</div>
) : (
conversationDocs.map(doc => (
<div
key={`${doc.filename}-${doc.uploadTime.getTime()}`}
className="w-full px-3 h-11 rounded-lg hover:bg-accent cursor-pointer group flex items-center"
>
<FileText className="h-4 w-4 mr-2 text-muted-foreground flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm text-foreground truncate">
{doc.filename}
</div>
</div>
</div>
))
)}
</div>
</div> */}
<div className="flex-shrink-0 mt-4"> <div className="flex-shrink-0 mt-4">
<div className="flex items-center justify-between mb-3 mx-3"> <div className="flex items-center justify-between mb-3 mx-3">
<h3 className="text-xs font-medium text-muted-foreground"> <h3 className="text-xs font-medium text-muted-foreground">
@ -595,7 +477,7 @@ export function Navigation({
</h3> </h3>
</div> </div>
<div className="overflow-y-auto scrollbar-hide space-y-1"> <div className="overflow-y-auto scrollbar-hide space-y-1">
{newConversationFiles?.length === 0 ? ( {(newConversationFiles?.length ?? 0) === 0 ? (
<div className="text-[13px] text-muted-foreground py-2 px-3"> <div className="text-[13px] text-muted-foreground py-2 px-3">
No documents yet No documents yet
</div> </div>

View file

@ -28,12 +28,16 @@ export const UI_CONSTANTS = {
export const ANIMATION_DURATION = 0.4; export const ANIMATION_DURATION = 0.4;
export const SIDEBAR_WIDTH = 280; export const SIDEBAR_WIDTH = 280;
export const HEADER_HEIGHT = 54; export const HEADER_HEIGHT = 54;
export const TOTAL_ONBOARDING_STEPS = 4; export const TOTAL_ONBOARDING_STEPS = 5;
/** /**
* Local Storage Keys * Local Storage Keys
*/ */
export const ONBOARDING_STEP_KEY = "onboarding_current_step"; export const ONBOARDING_STEP_KEY = "onboarding_current_step";
export const ONBOARDING_ASSISTANT_MESSAGE_KEY = "onboarding_assistant_message";
export const ONBOARDING_SELECTED_NUDGE_KEY = "onboarding_selected_nudge";
export const ONBOARDING_CARD_STEPS_KEY = "onboarding_card_steps";
export const ONBOARDING_UPLOAD_STEPS_KEY = "onboarding_upload_steps";
export const FILES_REGEX = export const FILES_REGEX =
/(?<=I'm uploading a document called ['"])[^'"]+\.[^.]+(?=['"]\. Here is its content:)/; /(?<=I'm uploading a document called ['"])[^'"]+\.[^.]+(?=['"]\. Here is its content:)/;