Merge pull request #1015 from khoj-ai/features/clean-up-authenticated-data

- De facto, was being assumed everywhere if authenticatedData is null, that it's not logged in. This isn't true because the data can still be loading. Update the hook to send additional states.
- Bonus: Delete model picker code and a slew of unused imports.
This commit is contained in:
sabaimran
2024-12-24 09:51:39 -08:00
committed by GitHub
18 changed files with 204 additions and 349 deletions

View File

@@ -140,11 +140,14 @@ function CreateAgentCard(props: CreateAgentCardProps) {
Create Agent
</div>
</DialogTrigger>
<DialogContent className={"lg:max-w-screen-lg overflow-y-scroll max-h-screen"}>
<DialogContent
className={
"lg:max-w-screen-lg py-4 overflow-y-scroll h-full md:h-4/6 rounded-lg flex flex-col"
}
>
<DialogHeader>Create Agent</DialogHeader>
{!props.userProfile && showLoginPrompt && (
<LoginPrompt
loginRedirectMessage="Sign in to start chatting with a specialized agent"
onOpenChange={setShowLoginPrompt}
isMobileWidth={props.isMobileWidth}
/>
@@ -174,7 +177,11 @@ export default function Agents() {
const { data, error, mutate } = useSWR<AgentData[]>("agents", agentsFetcher, {
revalidateOnFocus: false,
});
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const { userConfig } = useUserConfig(true);
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
const isMobileWidth = useIsMobileWidth();
@@ -310,7 +317,11 @@ export default function Agents() {
input_tools: [],
output_modes: [],
}}
userProfile={authenticatedData}
userProfile={
authenticationLoading
? null
: (authenticatedData ?? null)
}
isMobileWidth={isMobileWidth}
filesOptions={filesData || []}
modelOptions={userConfig?.chat_model_options || []}
@@ -328,7 +339,6 @@ export default function Agents() {
</div>
{showLoginPrompt && (
<LoginPrompt
loginRedirectMessage="Sign in to start chatting with a specialized agent"
onOpenChange={setShowLoginPrompt}
isMobileWidth={isMobileWidth}
/>
@@ -345,53 +355,59 @@ export default function Agents() {
</Alert>
<div className="pt-6 md:pt-8">
<div className={`${styles.agentList}`}>
{personalAgents.map((agent) => (
<AgentCard
key={agent.slug}
data={agent}
userProfile={authenticatedData}
isMobileWidth={isMobileWidth}
filesOptions={filesData ?? []}
selectedChatModelOption={defaultModelOption?.name || ""}
isSubscribed={isSubscribed}
setAgentChangeTriggered={setAgentChangeTriggered}
modelOptions={userConfig?.chat_model_options || []}
editCard={true}
agentSlug={agentSlug || ""}
inputToolOptions={
agentConfigurationOptions?.input_tools || {}
}
outputModeOptions={
agentConfigurationOptions?.output_modes || {}
}
/>
))}
{authenticatedData &&
personalAgents.map((agent) => (
<AgentCard
key={agent.slug}
data={agent}
userProfile={authenticatedData}
isMobileWidth={isMobileWidth}
filesOptions={filesData ?? []}
selectedChatModelOption={
defaultModelOption?.name || ""
}
isSubscribed={isSubscribed}
setAgentChangeTriggered={setAgentChangeTriggered}
modelOptions={userConfig?.chat_model_options || []}
editCard={true}
agentSlug={agentSlug || ""}
inputToolOptions={
agentConfigurationOptions?.input_tools || {}
}
outputModeOptions={
agentConfigurationOptions?.output_modes || {}
}
/>
))}
</div>
</div>
<div className="pt-6 md:pt-8">
<h2 className="text-2xl">Explore</h2>
<div className={`${styles.agentList}`}>
{publicAgents.map((agent) => (
<AgentCard
key={agent.slug}
data={agent}
userProfile={authenticatedData}
isMobileWidth={isMobileWidth}
editCard={false}
filesOptions={filesData ?? []}
selectedChatModelOption={defaultModelOption?.name || ""}
isSubscribed={isSubscribed}
setAgentChangeTriggered={setAgentChangeTriggered}
modelOptions={userConfig?.chat_model_options || []}
agentSlug={agentSlug || ""}
inputToolOptions={
agentConfigurationOptions?.input_tools || {}
}
outputModeOptions={
agentConfigurationOptions?.output_modes || {}
}
/>
))}
{!authenticationLoading &&
publicAgents.map((agent) => (
<AgentCard
key={agent.slug}
data={agent}
userProfile={authenticatedData || null}
isMobileWidth={isMobileWidth}
editCard={false}
filesOptions={filesData ?? []}
selectedChatModelOption={
defaultModelOption?.name || ""
}
isSubscribed={isSubscribed}
setAgentChangeTriggered={setAgentChangeTriggered}
modelOptions={userConfig?.chat_model_options || []}
agentSlug={agentSlug || ""}
inputToolOptions={
agentConfigurationOptions?.input_tools || {}
}
outputModeOptions={
agentConfigurationOptions?.output_modes || {}
}
/>
))}
</div>
</div>
</div>

View File

@@ -980,7 +980,11 @@ function AutomationComponentWrapper(props: AutomationComponentWrapperProps) {
}
export default function Automations() {
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const {
data: personalAutomations,
error,
@@ -1068,9 +1072,6 @@ export default function Automations() {
</div>
{showLoginPrompt && (
<LoginPrompt
loginRedirectMessage={
"Create an account to make your own automation"
}
onOpenChange={setShowLoginPrompt}
isMobileWidth={isMobileWidth}
/>
@@ -1114,7 +1115,7 @@ export default function Automations() {
<Suspense>
<SharedAutomationCard
isMobileWidth={isMobileWidth}
authenticatedData={authenticatedData}
authenticatedData={authenticatedData || null}
locationData={locationData}
isLoggedIn={authenticatedData ? true : false}
setShowLoginPrompt={setShowLoginPrompt}
@@ -1123,7 +1124,8 @@ export default function Automations() {
</Suspense>
{isLoading && <InlineLoading message="booting up your automations" />}
<div className={`${styles.automationsLayout}`}>
{personalAutomations &&
{authenticatedData &&
personalAutomations &&
personalAutomations.map((automation) => (
<AutomationsCard
isMobileWidth={isMobileWidth}
@@ -1135,17 +1137,18 @@ export default function Automations() {
setShowLoginPrompt={setShowLoginPrompt}
/>
))}
{allNewAutomations.map((automation) => (
<AutomationsCard
isMobileWidth={isMobileWidth}
key={automation.id}
authenticatedData={authenticatedData}
automation={automation}
locationData={locationData}
isLoggedIn={authenticatedData ? true : false}
setShowLoginPrompt={setShowLoginPrompt}
/>
))}
{authenticatedData &&
allNewAutomations.map((automation) => (
<AutomationsCard
isMobileWidth={isMobileWidth}
key={automation.id}
authenticatedData={authenticatedData}
automation={automation}
locationData={locationData}
isLoggedIn={authenticatedData ? true : false}
setShowLoginPrompt={setShowLoginPrompt}
/>
))}
</div>
<h3 className="text-xl py-4">Explore</h3>
<div className={`${styles.automationsLayout}`}>
@@ -1154,7 +1157,7 @@ export default function Automations() {
isMobileWidth={isMobileWidth}
setNewAutomationData={setNewAutomationData}
key={automation.id}
authenticatedData={authenticatedData}
authenticatedData={authenticatedData || null}
automation={automation}
locationData={locationData}
isLoggedIn={authenticatedData ? true : false}

View File

@@ -64,9 +64,10 @@ div.chatBody {
div.chatLayout {
display: grid;
grid-template-columns: auto 1fr;
grid-template-columns: 1fr;
gap: 1rem;
padding-top: 1rem;
width: 100%;
}
div.chatBox {

View File

@@ -193,7 +193,11 @@ export default function Chat() {
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
};
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const isMobileWidth = useIsMobileWidth();
useEffect(() => {
@@ -425,7 +429,7 @@ export default function Chat() {
<div className={styles.chatBoxBody}>
<Suspense fallback={<Loading />}>
<ChatBodyData
isLoggedIn={authenticatedData !== null}
isLoggedIn={authenticatedData ? true : false}
streamedMessages={messages}
setStreamedMessages={setMessages}
chatOptionsData={chatOptionsData}

View File

@@ -19,13 +19,15 @@ const fetcher = (url: string) =>
.catch((err) => console.warn(err));
export function useAuthenticatedData() {
const { data, error } = useSWR<UserProfile>("/api/v1/user", fetcher, {
const { data, error, isLoading } = useSWR<UserProfile>("/api/v1/user", fetcher, {
revalidateOnFocus: false,
});
if (error || !data || data.detail === "Forbidden") return null;
if (data?.detail === "Forbidden") {
return { data: null, error: "Forbidden", isLoading: false };
}
return data;
return { data, error, isLoading };
}
export interface ModelOptions {

View File

@@ -326,7 +326,6 @@ export function AgentCard(props: AgentCardProps) {
<Card className={`shadow-md rounded-xl hover:shadow-lg dark:bg-muted`}>
{showLoginPrompt && (
<LoginPrompt
loginRedirectMessage={`Sign in to start chatting with ${props.data.name}`}
onOpenChange={setShowLoginPrompt}
isMobileWidth={props.isMobileWidth}
/>
@@ -430,7 +429,7 @@ export function AgentCard(props: AgentCardProps) {
{props.editCard ? (
<DialogContent
className={
"lg:max-w-screen-lg py-4 overflow-y-scroll h-4/6 rounded-lg flex flex-col"
"lg:max-w-screen-lg py-4 overflow-y-scroll h-full md:h-4/6 rounded-lg flex flex-col"
}
>
<DialogTitle>
@@ -536,6 +535,8 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
const basicFields = [
{ name: "name", label: "Name" },
{ name: "persona", label: "Personality" },
{ name: "color", label: "Color" },
{ name: "icon", label: "Icon" },
];
const toolsFields = [
@@ -546,17 +547,15 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
const knowledgeBaseFields = [{ name: "files", label: "Knowledge Base" }];
const customizationFields = [
{ name: "color", label: "Color" },
{ name: "icon", label: "Icon" },
{ name: "chat_model", label: "Chat Model" },
{ name: "privacy_level", label: "Privacy Level" },
];
const formGroups = [
{ fields: basicFields, label: "Basic Settings", tabName: "basic" },
{ fields: customizationFields, label: "Customization & Access", tabName: "customize" },
{ fields: knowledgeBaseFields, label: "Knowledge Base", tabName: "knowledge" },
{ fields: toolsFields, label: "Tools Settings", tabName: "tools" },
{ fields: basicFields, label: "1. Basic Settings", tabName: "basic" },
{ fields: customizationFields, label: "2. Model & Privacy", tabName: "customize" },
{ fields: knowledgeBaseFields, label: "3. Knowledge Base", tabName: "knowledge" },
{ fields: toolsFields, label: "4. Tools", tabName: "tools" },
];
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -755,7 +754,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="chat_model"
render={({ field }) => (
<FormItem className="my-3 grid gap-2">
<FormItem className="my-2 grid gap-2">
<FormLabel>Chat Model</FormLabel>
<FormDescription>
{!props.isSubscribed ? (
@@ -802,7 +801,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="privacy_level"
render={({ field }) => (
<FormItem className="my-3 grid gap-2">
<FormItem className="my-2 grid gap-2">
<FormLabel>
<div>Privacy Level</div>
</FormLabel>
@@ -859,7 +858,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="color"
render={({ field }) => (
<FormItem className="space-y-3">
<FormItem className="space-y-3 my-2">
<FormLabel>Color</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
@@ -893,7 +892,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="icon"
render={({ field }) => (
<FormItem className="space-y-3">
<FormItem className="space-y-3 my-2">
<FormLabel>Icon</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
@@ -929,12 +928,12 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="persona"
render={({ field }) => (
<FormItem className="space-y-1 grid gap-2">
<FormItem className="space-y-1 my-2 grid gap-2">
<FormLabel>Personality</FormLabel>
<FormDescription>
What is the personality, thought process, or tuning of this
agent? Get creative; this is how you can influence the agent
constitution.
agent? This is where you can provide any instructions to the
agent.
</FormDescription>
<FormControl>
<Textarea
@@ -955,7 +954,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
control={props.form.control}
name="files"
render={({ field }) => (
<FormItem className="flex flex-col gap-2">
<FormItem className="my-2 flex flex-col gap-2">
<FormLabel>Knowledge Base</FormLabel>
<FormDescription>
Which information should be part of its digital brain?{" "}
@@ -1260,7 +1259,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
<Form {...props.form}>
<form
onSubmit={props.form.handleSubmit(handleSubmit)}
className="space-y-6 h-full flex flex-col justify-between"
className="space-y-6 pb-4 h-full flex flex-col justify-between"
>
<Tabs defaultValue="basic" value={formGroups[currentStep].tabName}>
<TabsList className="grid grid-cols-2 md:grid-cols-4 gap-2 h-fit">
@@ -1268,13 +1267,15 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
<TabsTrigger
key={group.tabName}
value={group.tabName}
className={`text-center ${areRequiredFieldsCompletedForCurrentStep(group) ? "" : "text-red-500"}`}
onClick={() =>
setCurrentStep(
formGroups.findIndex((g) => g.tabName === group.tabName),
)
}
>
{group.label}
{group.label}{" "}
{!areRequiredFieldsCompletedForCurrentStep(group) && "*"}
</TabsTrigger>
))}
</TabsList>
@@ -1305,7 +1306,7 @@ export function AgentModificationForm(props: AgentModificationFormProps) {
}
className={`items-center ${isSaving ? "bg-stone-100 dark:bg-neutral-900" : ""} text-white ${colorOptionClassName}`}
>
Next
Continue
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
) : (

View File

@@ -3,7 +3,6 @@
import styles from "./sidePanel.module.css";
import { useEffect, useMemo, useState } from "react";
import { useRef } from "react";
import { mutate } from "swr";
@@ -102,14 +101,10 @@ import {
} from "@/components/ui/alert-dialog";
import { modifyFileFilterForConversation } from "@/app/common/chatFunctions";
import { ScrollAreaScrollbar } from "@radix-ui/react-scroll-area";
import { KhojLogoType } from "@/app/components/logo/khojLogo";
import NavMenu from "@/app/components/navMenu/navMenu";
import { getIconFromIconName } from "@/app/common/iconUtils";
import LoginPrompt from "../loginPrompt/loginPrompt";
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
@@ -888,13 +883,9 @@ const fetchChatHistory = async (url: string) => {
};
export const useChatSessionsFetchRequest = (url: string) => {
const { data, error } = useSWR<ChatHistory[]>(url, fetchChatHistory);
const { data, isLoading, error } = useSWR<ChatHistory[]>(url, fetchChatHistory);
return {
data,
isLoading: !error && !data,
isError: error,
};
return { data, isLoading, error };
};
interface SidePanelProps {
@@ -908,9 +899,12 @@ export default function AllConversations(props: SidePanelProps) {
const [data, setData] = useState<ChatHistory[] | null>(null);
const [organizedData, setOrganizedData] = useState<GroupedChatHistory | null>(null);
const [subsetOrganizedData, setSubsetOrganizedData] = useState<GroupedChatHistory | null>(null);
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const { data: chatSessions, isLoading } = useChatSessionsFetchRequest(
authenticatedData ? `/api/chat/sessions` : "",
);
@@ -967,10 +961,12 @@ export default function AllConversations(props: SidePanelProps) {
return (
<SidebarGroup>
<SidebarGroupLabel className="!p-0 m-0 px-0">Conversations</SidebarGroupLabel>
<div className={`flex justify-between flex-col`}>
{authenticatedData && (
<>
<SidebarGroupLabel className="!p-0 m-0 px-0">
Conversations
</SidebarGroupLabel>
<div
className={`${props.sideBarOpen ? "border-l-2 border-light-blue-500 border-opacity-25 " : ""}`}
>

View File

@@ -1,18 +1,14 @@
import { Calendar, Home, Inbox, Search, Settings } from "lucide-react";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import Link from "next/link";
import {
KhojAgentLogo,
KhojAutomationLogo,
@@ -21,12 +17,15 @@ import {
KhojSearchLogo,
} from "../logo/khojLogo";
import { Gear } from "@phosphor-icons/react/dist/ssr";
import { House, Plus } from "@phosphor-icons/react";
import { Plus } from "@phosphor-icons/react";
import { useEffect, useState } from "react";
import { useAuthenticatedData } from "@/app/common/auth";
import AllConversations from "../allConversations/allConversations";
import NavMenu from "../navMenu/navMenu";
import FooterMenu from "../navMenu/navMenu";
import { useSidebar } from "@/components/ui/sidebar";
import { useIsMobileWidth } from "@/app/common/utils";
import { UserPlusIcon } from "lucide-react";
import { useAuthenticatedData } from "@/app/common/auth";
import LoginPrompt from "../loginPrompt/loginPrompt";
// Menu items.
const items = [
@@ -66,23 +65,22 @@ interface AppSidebarProps {
}
export function AppSidebar(props: AppSidebarProps) {
const [isMobileWidth, setIsMobileWidth] = useState(false);
const isMobileWidth = useIsMobileWidth();
const { data, isLoading, error } = useAuthenticatedData();
const { state, open, setOpen, openMobile, setOpenMobile, isMobile, toggleSidebar } =
useSidebar();
useEffect(() => {
const handleResize = () => {
setIsMobileWidth(window.innerWidth < 768);
};
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
useEffect(() => {
if (!isLoading && !data) {
setShowLoginPrompt(true);
}
}, [isLoading, data]);
return (
<Sidebar collapsible={"icon"} variant="sidebar">
<Sidebar collapsible={"icon"} variant="sidebar" className="md:py-2">
<SidebarHeader>
<SidebarMenu className="p-0 m-0">
<SidebarMenuItem className="p-0 m-0">
@@ -96,7 +94,6 @@ export function AppSidebar(props: AppSidebarProps) {
<SidebarMenuButton asChild>
<a className="flex items-center gap-2 no-underline" href="/">
<KhojLogo className="w-14 h-auto" />
<span className="text-lg">Khoj</span>
</a>
</SidebarMenuButton>
)}
@@ -104,9 +101,29 @@ export function AppSidebar(props: AppSidebarProps) {
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
{showLoginPrompt && (
<LoginPrompt
onOpenChange={(isOpen) => setShowLoginPrompt(isOpen)}
isMobileWidth={isMobileWidth}
/>
)}
<SidebarGroup>
<SidebarGroupContent>
<SidebarMenu className="p-0 m-0">
{!isLoading && !data && (
<SidebarMenuItem className="p-0 m-0 list-none">
<SidebarMenuButton
asChild
variant={"default"}
onClick={() => setShowLoginPrompt(true)}
>
<div>
<UserPlusIcon />
<span>Sign up to get started</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
)}
{items.map((item) => (
<SidebarMenuItem key={item.title} className="p-0 list-none m-0">
<SidebarMenuButton asChild>
@@ -131,7 +148,7 @@ export function AppSidebar(props: AppSidebarProps) {
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<NavMenu sideBarIsOpen={open} />
<FooterMenu sideBarIsOpen={open} />
</SidebarFooter>
</Sidebar>
);

View File

@@ -409,7 +409,6 @@ export const ChatInputArea = forwardRef<HTMLTextAreaElement, ChatInputProps>((pr
<LoginPrompt
onOpenChange={setShowLoginPrompt}
isMobileWidth={props.isMobileWidth}
loginRedirectMessage={loginRedirectMessage}
/>
)}
{uploading && (

View File

@@ -29,7 +29,6 @@ import { Card, CardContent } from "@/components/ui/card";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
export interface LoginPromptProps {
loginRedirectMessage: string;
onOpenChange: (open: boolean) => void;
isMobileWidth?: boolean;
}

View File

@@ -1,23 +0,0 @@
select.modelPicker {
font-size: small;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
padding-right: 0.75rem;
border: none;
border-width: 1px;
display: flex;
align-items: center;
height: 2.5rem;
justify-content: space-between;
border-radius: calc(0.5rem - 2px);
}
select.modelPicker:after {
grid-area: select;
justify-self: end;
}
div.modelPicker {
margin-top: 8px;
}

View File

@@ -1,166 +0,0 @@
import { useAuthenticatedData } from "@/app/common/auth";
import React, { useEffect } from "react";
import useSWR from "swr";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import styles from "./modelPicker.module.css";
export interface Model {
id: number;
chat_model: string;
}
// Custom fetcher function to fetch options
const fetchOptionsRequest = async (url: string) => {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response.json();
};
export const useOptionsRequest = (url: string) => {
const { data, error } = useSWR<Model[]>(url, fetchOptionsRequest);
return {
data,
isLoading: !error && !data,
isError: error,
};
};
const fetchSelectedModel = async (url: string) => {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response.json();
};
export const useSelectedModel = (url: string) => {
const { data, error } = useSWR<Model>(url, fetchSelectedModel);
return {
data,
isLoading: !error && !data,
isError: error,
};
};
interface ModelPickerProps {
disabled?: boolean;
setModelUsed?: (model: Model) => void;
initialModel?: Model;
}
export const ModelPicker: React.FC<any> = (props: ModelPickerProps) => {
const { data: models } = useOptionsRequest("/api/model/chat/options");
const { data: selectedModel } = useSelectedModel("/api/model/chat");
const [openLoginDialog, setOpenLoginDialog] = React.useState(false);
let userData = useAuthenticatedData();
const setModelUsed = props.setModelUsed;
useEffect(() => {
if (setModelUsed && selectedModel) {
setModelUsed(selectedModel);
}
}, [selectedModel, setModelUsed]);
if (!models) {
return <div>Loading...</div>;
}
function onSelect(model: Model) {
if (!userData) {
setOpenLoginDialog(true);
return;
}
if (props.setModelUsed) {
props.setModelUsed(model);
}
fetch("/api/model/chat" + "?id=" + String(model.id), {
method: "POST",
body: JSON.stringify(model),
})
.then((response) => {
if (!response.ok) {
throw new Error("Failed to select model");
}
})
.catch((error) => {
console.error("Failed to select model", error);
});
}
function isSelected(model: Model) {
if (props.initialModel) {
return model.id === props.initialModel.id;
}
return selectedModel?.id === model.id;
}
return (
<div className={styles.modelPicker}>
<select
className={styles.modelPicker}
onChange={(e) => {
const selectedModelId = Number(e.target.value);
const selectedModel = models.find((model) => model.id === selectedModelId);
if (selectedModel) {
onSelect(selectedModel);
} else {
console.error("Selected model not found", e.target.value);
}
}}
disabled={props.disabled}
>
{models?.map((model) => (
<option key={model.id} value={model.id} selected={isSelected(model)}>
{model.chat_model}
</option>
))}
</select>
<AlertDialog open={openLoginDialog} onOpenChange={setOpenLoginDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
You must be logged in to configure your model.
</AlertDialogTitle>
<AlertDialogDescription>
Once you create an account with Khoj, you can configure your model and
use a whole suite of other features. Check out our{" "}
<a href="https://docs.khoj.dev/">documentation</a> to learn more.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
window.location.href = window.location.origin + "/login";
}}
>
Sign in
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
};

View File

@@ -1,20 +1,10 @@
"use client";
import styles from "./navMenu.module.css";
import Link from "next/link";
import { useAuthenticatedData } from "@/app/common/auth";
import { useState, useEffect } from "react";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import {
Menubar,
MenubarContent,
MenubarItem,
MenubarMenu,
MenubarSeparator,
MenubarTrigger,
} from "@/components/ui/menubar";
import {
DropdownMenu,
DropdownMenuContent,
@@ -22,8 +12,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Moon, Sun, UserCircle, Question, GearFine, ArrowRight, Code } from "@phosphor-icons/react";
import { KhojAgentLogo, KhojAutomationLogo, KhojSearchLogo } from "../logo/khojLogo";
import { Moon, Sun, UserCircle, Question, ArrowRight, Code } from "@phosphor-icons/react";
import { useIsMobileWidth } from "@/app/common/utils";
import LoginPrompt from "../loginPrompt/loginPrompt";
import { Button } from "@/components/ui/button";
@@ -54,12 +43,16 @@ interface NavMenuProps {
sideBarIsOpen: boolean;
}
export default function NavMenu({ sideBarIsOpen }: NavMenuProps) {
const userData = useAuthenticatedData();
export default function FooterMenu({ sideBarIsOpen }: NavMenuProps) {
const {
data: userData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const [darkMode, setDarkMode] = useState(false);
const [initialLoadDone, setInitialLoadDone] = useState(false);
const isMobileWidth = useIsMobileWidth();
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
const isMobileWidth = useIsMobileWidth();
useEffect(() => {
if (localStorage.getItem("theme") === "dark") {
@@ -97,6 +90,12 @@ export default function NavMenu({ sideBarIsOpen }: NavMenuProps) {
return (
<SidebarMenu className="border-none p-0 m-0">
<SidebarMenuItem className="p-0 m-0">
{showLoginPrompt && (
<LoginPrompt
onOpenChange={(isOpen) => setShowLoginPrompt(isOpen)}
isMobileWidth={isMobileWidth}
/>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton className="p-0 m-0 rounded-lg" asChild>
@@ -107,13 +106,13 @@ export default function NavMenu({ sideBarIsOpen }: NavMenuProps) {
>
<AvatarImage src={userData?.photo} alt="user profile" />
<AvatarFallback className="bg-transparent hover:bg-muted">
{userData?.username[0].toUpperCase()}
{userData.username[0].toUpperCase()}
</AvatarFallback>
</Avatar>
{sideBarIsOpen && (
<>
<p>{userData?.username}</p>
<ChevronUp className="w-6 h-6" />
<ChevronUp className="w-6 h-6 ml-auto" />
</>
)}
</span>

View File

@@ -3,9 +3,6 @@ import { noto_sans, noto_sans_arabic } from "@/app/fonts";
import "./globals.css";
import { ContentSecurityPolicy } from "./common/layoutHelper";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AppSidebar } from "@/app/components/appSidebar/appSidebar";
export const metadata: Metadata = {
title: "Khoj AI - Ask Anything",
description:

View File

@@ -222,7 +222,6 @@ function ChatBodyData(props: ChatBodyDataProps) {
<LoginPrompt
onOpenChange={setShowLoginPrompt}
isMobileWidth={props.isMobileWidth}
loginRedirectMessage={"Login to your second brain"}
/>
)}
{!props.isLoggedIn && (
@@ -425,7 +424,11 @@ export default function Home() {
const { userConfig: initialUserConfig, isLoadingUserConfig } = useUserConfig(true);
const [userConfig, setUserConfig] = useState<UserConfig | null>(null);
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const handleConversationIdChange = (newConversationId: string) => {
setConversationID(newConversationId);
@@ -477,15 +480,17 @@ export default function Home() {
<title>Khoj AI - Your Second Brain</title>
<div className={`${styles.chatBox}`}>
<div className={`${styles.chatBoxBody}`}>
<ChatBodyData
isLoggedIn={authenticatedData !== null}
chatOptionsData={chatOptionsData}
setUploadedFiles={setUploadedFiles}
isMobileWidth={isMobileWidth}
onConversationIdChange={handleConversationIdChange}
userConfig={userConfig}
isLoadingUserConfig={isLoadingUserConfig}
/>
{!authenticationLoading && (
<ChatBodyData
isLoggedIn={authenticatedData ? true : false}
chatOptionsData={chatOptionsData}
setUploadedFiles={setUploadedFiles}
isMobileWidth={isMobileWidth}
onConversationIdChange={handleConversationIdChange}
userConfig={userConfig}
isLoadingUserConfig={isLoadingUserConfig}
/>
)}
</div>
</div>
</div>

View File

@@ -38,7 +38,6 @@ import {
Key,
Palette,
UserCircle,
FileMagnifyingGlass,
Trash,
Copy,
CreditCard,
@@ -499,7 +498,6 @@ enum PhoneNumberValidationState {
}
export default function SettingsView() {
const [title, setTitle] = useState("Settings");
const { apiKeys, generateAPIKey, copyAPIKey, deleteAPIKey } = useApiKeys();
const { userConfig: initialUserConfig } = useUserConfig(true);
const [userConfig, setUserConfig] = useState<UserConfig | null>(null);
@@ -514,6 +512,8 @@ export default function SettingsView() {
const { toast } = useToast();
const isMobileWidth = useIsMobileWidth();
const title = "Settings";
const cardClassName =
"w-full lg:w-1/3 grid grid-flow-column border border-gray-300 shadow-md rounded-lg border dark:border-none dark:bg-muted border-opacity-50";

View File

@@ -123,7 +123,11 @@ export default function SharedChat() {
const [paramSlug, setParamSlug] = useState<string | undefined>(undefined);
const [images, setImages] = useState<string[]>([]);
const authenticatedData = useAuthenticatedData();
const {
data: authenticatedData,
error: authenticationError,
isLoading: authenticationLoading,
} = useAuthenticatedData();
const isMobileWidth = useIsMobileWidth();
useEffect(() => {
@@ -222,7 +226,7 @@ export default function SharedChat() {
conversationId={conversationId}
streamedMessages={messages}
setQueryToProcess={setQueryToProcess}
isLoggedIn={authenticatedData !== null}
isLoggedIn={authenticatedData ? true : false}
publicConversationSlug={paramSlug}
chatOptionsData={chatOptionsData}
setTitle={setTitle}

View File

@@ -62,6 +62,7 @@ div.chatLayout {
display: grid;
grid-template-columns: auto 1fr;
gap: 1rem;
width: 100%;
}
div.chatBox {