Spaces:
Sleeping
Sleeping
feat: Setup postgres and prisma (#50)
Browse fileshttps://vercel.com/landing-platform/~/stores/postgres/store_kmMuRzKbVnJ5IGpL/guides
<img width="311" alt="image"
src="https://github.com/landing-ai/vision-agent-ui/assets/5669963/2bceb4d8-cbfd-45ea-a98e-97220f718d70">
**Server function to migrate**
- [DONE] Create user
- [DONE] Logout user create Chat with init message
- [DONE] Logout out user create message into existing chat
- [DONE] Login user show chat history
- [DONE] Login user create message into existing chat
- [DONE] Delete Chat
Files changed (25)
- app/all/chat/[id]/page.tsx+7-5
- app/all/layout.tsx+26-26
- app/api/auth/[...nextauth]/route.ts+1-1
- app/api/upload/route.ts → app/api/chat/create/route.tsRenamed+11-26
- app/api/vision-agent/route.ts+3-3
- app/chat/[id]/page.tsx+6-3
- app/chat/layout.tsx+4-4
- app/chat/page.tsx+8-6
- app/project/layout.tsx+2-2
- auth.ts+31-13
- components/Header.tsx+4-4
- components/chat-sidebar/ChatCard.tsx+7-8
- components/chat-sidebar/ChatListSidebar.tsx+2-2
- components/chat/ImageSelector.tsx+3-2
- components/chat/index.tsx+4-4
- components/project/ProjectChat.tsx+37-39
- components/ui/Icons.tsx+2-2
- lib/db/functions.tsAdded+145
- lib/db/prisma.tsAdded+5
- lib/db/types.tsAdded+8
- lib/hooks/useVisionAgent.ts+27-32
- lib/kv/chat.ts+118-118
- package.json+5-2
- pnpm-lock.yaml+64
- prisma/schema.prismaAdded+59
1234562 unmodified lines910111213141516import { getKVChat } from '@/lib/kv/chat';import { Chat } from '@/components/chat';import { auth } from '@/auth';interface PageProps {params: {2 unmodified lines}export default async function Page({ params }: PageProps) {const { id: chatId } = params;const chat = await getKVChat(chatId);const session = await auth();return <Chat chat={chat} session={session} isAdminView />;}12345672 unmodified lines101112131415161718import { Chat } from '@/components/chat';import { auth } from '@/auth';import { dbGetChat } from '@/lib/db/functions';import { redirect } from 'next/navigation';interface PageProps {params: {2 unmodified lines}export default async function Page({ params }: PageProps) {return <div>TO BE FIXED</div>;// const { id: chatId } = params;// const chat = await getKVChat(chatId);// const session = await auth();// return <Chat chat={chat} session={session} isAdminView />;}
123456781 unmodified line101112131415161718192021222324252627282930313233343536373839import { Suspense } from 'react';import Loading from '@/components/ui/Loading';import { authEmail } from '@/auth';import { redirect } from 'next/navigation';import { adminGetAllKVChats } from '@/lib/kv/chat';import ChatSidebarList from '@/components/chat-sidebar/ChatListSidebar';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {const { isAdmin, user } = await authEmail();if (!isAdmin) {redirect('/');}const chats = await adminGetAllKVChats();return (<div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden">{user && (<divdata-state="open"className="peer absolute inset-y-0 z-30 hidden border-r bg-muted duration-300 ease-in-out translate-x-0 lg:flex lg:w-[250px] xl:w-[300px] h-full flex-col dark:bg-zinc-950 overflow-auto py-2"><Suspense fallback={<Loading />}><ChatSidebarList chats={chats} isAdminView /></Suspense></div>)}<Suspense fallback={<Loading />}><div className="group w-full overflow-auto pl-0 animate-in duration-300 ease-in-out peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]">{children}</div></Suspense></div>);}12345671 unmodified line9101112131415161718192021222324252627282930313233343536373839import { Suspense } from 'react';import Loading from '@/components/ui/Loading';import { sessionUser } from '@/auth';import { redirect } from 'next/navigation';import ChatSidebarList from '@/components/chat-sidebar/ChatListSidebar';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {return <div>TO BE FIXED</div>;// const { isAdmin, user } = await sessionUser();// if (!isAdmin) {// redirect('/');// }// const chats = await adminGetAllKVChats();// return (// <div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden">// {user && (// <div// data-state="open"// className="peer absolute inset-y-0 z-30 hidden border-r bg-muted duration-300 ease-in-out translate-x-0 lg:flex lg:w-[250px] xl:w-[300px] h-full flex-col dark:bg-zinc-950 overflow-auto py-2"// >// <Suspense fallback={<Loading />}>// <ChatSidebarList chats={chats} isAdminView />// </Suspense>// </div>// )}// <Suspense fallback={<Loading />}>// <div className="group w-full overflow-auto pl-0 animate-in duration-300 ease-in-out peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]">// {children}// </div>// </Suspense>// </div>// );}
12export { GET, POST } from '@/auth';export const runtime = 'edge';12export { GET, POST } from '@/auth';// export const runtime = 'edge';
1234567892 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647import { auth } from '@/auth';import { createKVChat } from '@/lib/kv/chat';import { withLogging } from '@/lib/logger';import { ChatEntity, MessageBase } from '@/lib/types';import { nanoid } from '@/lib/utils';import { Session } from 'next-auth';import { revalidatePath } from 'next/cache';/**2 unmodified lines*/export const POST = withLogging(async (session,json: {id?: string;url: string;initMessages?: MessageBase[];},): Promise<Response> => {const user = session?.user?.email ?? 'anonymous';// if (!email) {// return new Response('Unauthorized', {// status: 401,// });// }try {const { id, url, initMessages } = json;const payload: ChatEntity = {url,id: id ?? nanoid(),user,messages: initMessages ?? [],updatedAt: Date.now(),};await createKVChat(payload);revalidatePath('/chat', 'layout');return Response.json(payload);} catch (error) {return new Response((error as Error).message, {status: 400,1234562 unmodified lines91011121314151617181920212223242526272829303132import { dbPostCreateChat } from '@/lib/db/functions';import { MessageRaw } from '@/lib/db/types';import { withLogging } from '@/lib/logger';import { revalidatePath } from 'next/cache';/**2 unmodified lines*/export const POST = withLogging(async (_session,json: {id?: string;url: string;initMessages?: MessageRaw[];},): Promise<Response> => {try {const { url, id, initMessages } = json;const response = await dbPostCreateChat({id,mediaUrl: url,initMessages,});revalidatePath('/chat', 'layout');return Response.json(response);} catch (error) {return new Response((error as Error).message, {status: 400,
15 unmodified lines16171819202122232425262725 unmodified lines5354555657585915 unmodified linesjson: {messages: MessageBase[];id: string;url: string;enableSelfReflection: boolean;},request,) => {const { messages, url, enableSelfReflection } = json;// const session = await auth();// if (!session?.user?.email) {25 unmodified lines}),),);formData.append('image', url);const fetchResponse = await fetch(`https://api.dev.landing.ai/v1/agent/chat?agent_class=vision_agent&visualize_output=true&self_reflection=${enableSelfReflection}`,15 unmodified lines16171819202122232425262725 unmodified lines5354555657585915 unmodified linesjson: {messages: MessageBase[];id: string;mediaUrl: string;enableSelfReflection: boolean;},request,) => {const { messages, mediaUrl, enableSelfReflection } = json;// const session = await auth();// if (!session?.user?.email) {25 unmodified lines}),),);formData.append('image', mediaUrl);const fetchResponse = await fetch(`https://api.dev.landing.ai/v1/agent/chat?agent_class=vision_agent&visualize_output=true&self_reflection=${enableSelfReflection}`,
12345673 unmodified lines11121314151617import { getKVChat } from '@/lib/kv/chat';import { Chat } from '@/components/chat';import { auth } from '@/auth';import { Session } from 'next-auth';interface PageProps {params: {3 unmodified linesexport default async function Page({ params }: PageProps) {const { id: chatId } = params;const chat = await getKVChat(chatId);const session = await auth();return <Chat chat={chat} session={session} />;}12345673 unmodified lines11121314151617181920import { Chat } from '@/components/chat';import { auth } from '@/auth';import { dbGetChat } from '@/lib/db/functions';import { redirect } from 'next/navigation';interface PageProps {params: {3 unmodified linesexport default async function Page({ params }: PageProps) {const { id: chatId } = params;const chat = await dbGetChat(chatId);if (!chat) {redirect('/');}const session = await auth();return <Chat chat={chat} session={session} />;}
12345671 unmodified line910111213141516import { authEmail } from '@/auth';import ChatSidebarList from '@/components/chat-sidebar/ChatListSidebar';import Loading from '@/components/ui/Loading';import { getKVChats } from '@/lib/kv/chat';import { Suspense } from 'react';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {const { email, user } = await authEmail();const chats = await getKVChats();return (<div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden">12345671 unmodified line910111213141516import { sessionUser } from '@/auth';import ChatSidebarList from '@/components/chat-sidebar/ChatListSidebar';import Loading from '@/components/ui/Loading';import { dbGetAllChat } from '@/lib/db/functions';import { Suspense } from 'react';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {const { email, user, id } = await sessionUser();const chats = await dbGetAllChat();return (<div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden">
1 unmodified line23456786 unmodified lines1516171819202122232425265 unmodified lines3233343536373852 unmodified lines919293949596971 unmodified lineimport ImageSelector from '@/components/chat/ImageSelector';import { generateInputImageMarkdown } from '@/lib/messageUtils';import { ChatEntity } from '@/lib/types';import { fetcher } from '@/lib/utils';import { useRouter } from 'next/navigation';6 unmodified linesimport Link from 'next/link';import { Button } from '@/components/ui/Button';import Img from '@/components/ui/Img';// const EXAMPLE_URL = 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/cereal-example.jpg';const EXAMPLE_URL = 'https://vision-agent-dev.s3.us-east-2.amazonaws.com/examples/flower.png';const EXAMPLE_HEADER = 'Counting and find';const EXAMPLE_SUBHEADER = 'number of flowers, area of largest and smallest flower';const EXAMPLE_PROMPT = 'Count the number of flowers and find the area of the largest and smallest flower';const exampleMessages = [{5 unmodified linesrole: 'user',content:EXAMPLE_PROMPT + '\n\n' + generateInputImageMarkdown(EXAMPLE_URL),id: 'fake-id-1',},],},52 unmodified linesindex > 1 && 'hidden md:block'}`}onClick={async () => {const resp = await fetcher<ChatEntity>('/api/upload', {method: 'POST',headers: {'Content-Type': 'application/json',1 unmodified line2345676 unmodified lines141516171819202122232425262728295 unmodified lines35363738394052 unmodified lines939495969798991 unmodified lineimport ImageSelector from '@/components/chat/ImageSelector';import { generateInputImageMarkdown } from '@/lib/messageUtils';import { fetcher } from '@/lib/utils';import { useRouter } from 'next/navigation';6 unmodified linesimport Link from 'next/link';import { Button } from '@/components/ui/Button';import Img from '@/components/ui/Img';import { ChatWithMessages } from '@/lib/db/types';// const EXAMPLE_URL = 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/cereal-example.jpg';const EXAMPLE_URL ='https://vision-agent-dev.s3.us-east-2.amazonaws.com/examples/flower.png';const EXAMPLE_HEADER = 'Counting and find';const EXAMPLE_SUBHEADER ='number of flowers, area of largest and smallest flower';const EXAMPLE_PROMPT ='Count the number of flowers and find the area of the largest and smallest flower';const exampleMessages = [{5 unmodified linesrole: 'user',content:EXAMPLE_PROMPT + '\n\n' + generateInputImageMarkdown(EXAMPLE_URL),},],},52 unmodified linesindex > 1 && 'hidden md:block'}`}onClick={async () => {const resp = await fetcher<ChatWithMessages>('/api/chat/create', {method: 'POST',headers: {'Content-Type': 'application/json',
12345671 unmodified line9101112131415import ProjectListSideBar from '@/components/project-sidebar/ProjectListSideBar';import { Suspense } from 'react';import Loading from '@/components/ui/Loading';import { authEmail } from '@/auth';import { redirect } from 'next/navigation';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {const { isAdmin } = await authEmail();if (!isAdmin) {redirect('/');12345671 unmodified line9101112131415import ProjectListSideBar from '@/components/project-sidebar/ProjectListSideBar';import { Suspense } from 'react';import Loading from '@/components/ui/Loading';import { sessionUser } from '@/auth';import { redirect } from 'next/navigation';interface ChatLayoutProps {1 unmodified line}export default async function Layout({ children }: ChatLayoutProps) {const { isAdmin } = await sessionUser();if (!isAdmin) {redirect('/');
12345618 unmodified lines25262728293031323334353637381 unmodified line404142434445464711 unmodified lines596061626364656667686970import NextAuth, { type DefaultSession } from 'next-auth';import GitHub from 'next-auth/providers/github';import Google from 'next-auth/providers/google';declare module 'next-auth' {interface Session {18 unmodified lines}),],callbacks: {// signIn({ profile }) {// if (profile?.email?.endsWith('@landing.ai')) {// return !!profile;// } else {// return '/unauthorized';// }// },jwt({ token, profile }) {if (profile) {token.id = profile.id || profile.sub;token.image = profile.avatar_url || profile.picture;1 unmodified linereturn token;},session: ({ session, token }) => {if (session?.user && token?.id) {session.user.id = String(token.id);}return session;},11 unmodified lines},});export async function authEmail() {const session = await auth();const email = session?.user?.email;return {email,isAdmin: !!email?.endsWith('landing.ai'),user: session?.user,};}1234567818 unmodified lines272829303132333435363738394041424344454647484950515253541 unmodified line56575859606162636411 unmodified lines76777879808182838485868788import NextAuth, { type DefaultSession } from 'next-auth';import GitHub from 'next-auth/providers/github';import Google from 'next-auth/providers/google';import { dbFindOrCreateUser } from './lib/db/functions';import { redirect } from 'next/navigation';declare module 'next-auth' {interface Session {18 unmodified lines}),],callbacks: {async signIn({ profile, user }) {if (!profile) {return false;}const { email, name } = profile;if (!email || !name) {return false;}const dbUser = await dbFindOrCreateUser(email, name);if (dbUser) {user.id = dbUser.id;return true;}return false;},async jwt({ token, profile, user }) {// console.log('[Ming] ~ jwt ~ user:', user, token);// const dbUser = await dbFindOrCreateUser(email, name);// console.log('[Ming] ~ signIn ~ dbUser:', dbUser);if (profile) {token.id = profile.id || profile.sub;token.image = profile.avatar_url || profile.picture;1 unmodified linereturn token;},session: ({ session, token }) => {if (token) {// put db user id into sessionsession.user.id = token.sub ?? '';}return session;},11 unmodified lines},});export async function sessionUser() {const session = await auth();const email = session?.user.email;return {email,isAdmin: !!email?.endsWith('landing.ai'),id: session?.user.id ?? null,user: session?.user ?? null,};}
12345677 unmodified lines1516171819202116 unmodified lines383940414243442 unmodified lines47484950515253import * as React from 'react';import Link from 'next/link';import { auth, authEmail } from '@/auth';import { Button } from '@/components/ui/Button';import { UserMenu } from '@/components/UserMenu';import {7 unmodified linesexport async function Header() {const session = await auth();const { isAdmin } = await authEmail();if (process.env.NEXT_PUBLIC_IS_HUGGING_FACE) {return (16 unmodified lines</TooltipTrigger><TooltipContent>New chat</TooltipContent></Tooltip> */}{isAdmin && (<Button variant="link" asChild className="mr-2"><Link href="/all">All Chats (Internal)</Link></Button>2 unmodified lines<Button variant="link" asChild className="mr-2"><Link href="/project">Projects (Internal)</Link></Button>)}<Button variant="link" asChild className="mr-2"><Link href="/chat">Chat</Link></Button>12345677 unmodified lines1516171819202116 unmodified lines383940414243442 unmodified lines47484950515253import * as React from 'react';import Link from 'next/link';import { auth, sessionUser } from '@/auth';import { Button } from '@/components/ui/Button';import { UserMenu } from '@/components/UserMenu';import {7 unmodified linesexport async function Header() {const session = await auth();const { isAdmin } = await sessionUser();if (process.env.NEXT_PUBLIC_IS_HUGGING_FACE) {return (16 unmodified lines</TooltipTrigger><TooltipContent>New chat</TooltipContent></Tooltip> */}{/* {isAdmin && (<Button variant="link" asChild className="mr-2"><Link href="/all">All Chats (Internal)</Link></Button>2 unmodified lines<Button variant="link" asChild className="mr-2"><Link href="/project">Projects (Internal)</Link></Button>)} */}<Button variant="link" asChild className="mr-2"><Link href="/chat">Chat</Link></Button>
3 unmodified lines45678910111213141516171819202115 unmodified lines373839404142439 unmodified lines53545556575859606162636465666768693 unmodified linesimport Link from 'next/link';import { useParams, usePathname, useRouter } from 'next/navigation';import { cn } from '@/lib/utils';import { ChatEntity } from '@/lib/types';import Image from 'next/image';import clsx from 'clsx';import Img from '../ui/Img';import { format } from 'date-fns';import { cleanInputMessage } from '@/lib/messageUtils';import { IconClose } from '../ui/Icons';import { removeKVChat } from '@/lib/kv/chat';// import { format } from 'date-fns';type ChatCardProps = PropsWithChildren<{chat: ChatEntity;isAdminView?: boolean;}>;15 unmodified linesconst ChatCard: React.FC<ChatCardProps> = ({ chat, isAdminView }) => {const { id: chatIdFromParam } = useParams();const { id, url, messages, user, updatedAt } = chat;if (!id) {return null;}9 unmodified linesclassNames={chatIdFromParam === id && 'border-gray-500'}><div className="overflow-hidden flex items-center size-full group"><Img src={url} alt={`chat-${id}-card-image`} className="w-1/4" /><div className="flex items-start flex-col h-full ml-3 w-3/4"><p className="text-sm mb-1">{title}</p><p className="text-xs text-gray-500">{updatedAt ? format(Number(updatedAt), 'yyyy-MM-dd') : '-'}</p>{isAdminView && <p className="text-xs text-gray-500">{user}</p>}<IconCloseonClick={async e => {e.stopPropagation();await removeKVChat(id);}}className="absolute right-4 opacity-0 group-hover:opacity-100 top-1/2 -translate-y-1/2"/>3 unmodified lines456789101112131415161718192015 unmodified lines363738394041429 unmodified lines52535455565758596061626364656667683 unmodified linesimport Link from 'next/link';import { useParams, usePathname, useRouter } from 'next/navigation';import { cn } from '@/lib/utils';import Image from 'next/image';import clsx from 'clsx';import Img from '../ui/Img';import { format } from 'date-fns';import { cleanInputMessage } from '@/lib/messageUtils';import { IconClose } from '../ui/Icons';import { ChatWithMessages } from '@/lib/db/types';import { dbDeleteChat } from '@/lib/db/functions';type ChatCardProps = PropsWithChildren<{chat: ChatWithMessages;isAdminView?: boolean;}>;15 unmodified linesconst ChatCard: React.FC<ChatCardProps> = ({ chat, isAdminView }) => {const { id: chatIdFromParam } = useParams();const { id, mediaUrl, messages, userId, updatedAt } = chat;if (!id) {return null;}9 unmodified linesclassNames={chatIdFromParam === id && 'border-gray-500'}><div className="overflow-hidden flex items-center size-full group"><Img src={mediaUrl} alt={`chat-${id}-card-image`} className="w-1/4" /><div className="flex items-start flex-col h-full ml-3 w-3/4"><p className="text-sm mb-1">{title}</p><p className="text-xs text-gray-500">{updatedAt ? format(Number(updatedAt), 'yyyy-MM-dd') : '-'}</p>{isAdminView && <p className="text-xs text-gray-500">{userId}</p>}<IconCloseonClick={async e => {e.stopPropagation();await dbDeleteChat(id);}}className="absolute right-4 opacity-0 group-hover:opacity-100 top-1/2 -translate-y-1/2"/>
2 unmodified lines34567891011121314152 unmodified linesimport ChatCard, { ChatCardLayout } from './ChatCard';import { IconPlus } from '../ui/Icons';import { auth } from '@/auth';import { ChatEntity } from '@/lib/types';import { VariableSizeList as List } from 'react-window';import { cleanInputMessage } from '@/lib/messageUtils';import AutoSizer from 'react-virtualized-auto-sizer';export interface ChatSidebarListProps {chats: ChatEntity[];isAdminView?: boolean;}2 unmodified lines34567891011121314152 unmodified linesimport ChatCard, { ChatCardLayout } from './ChatCard';import { IconPlus } from '../ui/Icons';import { auth } from '@/auth';import { VariableSizeList as List } from 'react-window';import { cleanInputMessage } from '@/lib/messageUtils';import AutoSizer from 'react-virtualized-auto-sizer';import { ChatWithMessages } from '@/lib/db/types';export interface ChatSidebarListProps {chats: ChatWithMessages[];isAdminView?: boolean;}
2 unmodified lines34567891 unmodified line11121314151669 unmodified lines868788899091922 unmodified linesimport React, { useCallback, useState } from 'react';import useImageUpload from '../../lib/hooks/useImageUpload';import { cn, fetcher } from '@/lib/utils';import { SignedPayload, MessageBase, ChatEntity } from '@/lib/types';import { useRouter } from 'next/navigation';import Loading from '../ui/Loading';import toast from 'react-hot-toast';1 unmodified linegenerateVideoThumbnails,getVideoCover,} from '@rajesh896/video-thumbnails-generator';export interface ImageSelectorProps {}69 unmodified linesreturn upload(thumbnailFile, resp.id);});}await fetcher<ChatEntity>('/api/upload', {method: 'POST',headers: {'Content-Type': 'application/json',2 unmodified lines34567891 unmodified line1112131415161769 unmodified lines878889909192932 unmodified linesimport React, { useCallback, useState } from 'react';import useImageUpload from '../../lib/hooks/useImageUpload';import { cn, fetcher } from '@/lib/utils';import { SignedPayload, MessageBase } from '@/lib/types';import { useRouter } from 'next/navigation';import Loading from '../ui/Loading';import toast from 'react-hot-toast';1 unmodified linegenerateVideoThumbnails,getVideoCover,} from '@rajesh896/video-thumbnails-generator';import { ChatWithMessages } from '@/lib/db/types';export interface ImageSelectorProps {}69 unmodified linesreturn upload(thumbnailFile, resp.id);});}await fetcher<ChatWithMessages>('/api/chat/create', {method: 'POST',headers: {'Content-Type': 'application/json',
1 unmodified line2345678910111213141516171819202116 unmodified lines383940414243441 unmodified lineimport { ChatList } from '@/components/chat/ChatList';import { Composer } from '@/components/chat/Composer';import { ChatEntity } from '@/lib/types';import useVisionAgent from '@/lib/hooks/useVisionAgent';import { useScrollAnchor } from '@/lib/hooks/useScrollAnchor';import { Session } from 'next-auth';import { useState } from 'react';export interface ChatProps extends React.ComponentProps<'div'> {chat: ChatEntity;isAdminView?: boolean;session: Session | null;}export function Chat({ chat, session, isAdminView }: ChatProps) {const { url, id } = chat;const { messages, append, reload, stop, isLoading, input, setInput } =useVisionAgent(chat);16 unmodified lines<div className="fixed inset-x-0 bottom-0 w-full animate-in duration-300 ease-in-out peer-[[data-state=open]]:group-[]:lg:pl-[250px] peer-[[data-state=open]]:group-[]:xl:pl-[300px] h-[178px]"><Composerid={id}url={url}isLoading={isLoading}stop={stop}append={append}1 unmodified line2345678910111213141516171819202116 unmodified lines383940414243441 unmodified lineimport { ChatList } from '@/components/chat/ChatList';import { Composer } from '@/components/chat/Composer';import useVisionAgent from '@/lib/hooks/useVisionAgent';import { useScrollAnchor } from '@/lib/hooks/useScrollAnchor';import { Session } from 'next-auth';import { useState } from 'react';import { ChatWithMessages } from '@/lib/db/types';export interface ChatProps extends React.ComponentProps<'div'> {chat: ChatWithMessages;isAdminView?: boolean;session: Session | null;}export function Chat({ chat, session, isAdminView }: ChatProps) {const { mediaUrl, id } = chat;const { messages, append, reload, stop, isLoading, input, setInput } =useVisionAgent(chat);16 unmodified lines<div className="fixed inset-x-0 bottom-0 w-full animate-in duration-300 ease-in-out peer-[[data-state=open]]:group-[]:lg:pl-[250px] peer-[[data-state=open]]:group-[]:xl:pl-[300px] h-[178px]"><Composerid={id}url={mediaUrl}isLoading={isLoading}stop={stop}append={append}
14 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585914 unmodified lines}const ProjectChat: React.FC<ChatProps> = ({ mediaList }) => {const selectedMediaId = useAtomValue(selectedMediaIdAtom);// fallback to the first mediaconst selectedMedia =mediaList.find(media => media.id === selectedMediaId) ?? mediaList[0];const { messages, append, reload, stop, isLoading, input, setInput } =useVisionAgent({url: selectedMedia.url,messages: [],user: 'does-not-matter@landing.ai',updatedAt: Date.now(),});const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } =useScrollAnchor();return (<><div className="h-full overflow-auto" ref={scrollRef}><div className="pb-[200px] pt-4 md:pt-10" ref={messagesRef}><ChatList messages={messages} session={null} isLoading={isLoading} /><div className="h-px w-full" ref={visibilityRef} /></div></div><div className="absolute inset-x-0 bottom-0 w-full h-[178px]"><Composerurl={selectedMedia.url}isLoading={isLoading}stop={stop}append={append}reload={reload}messages={messages}input={input}setInput={setInput}isAtBottom={isAtBottom}scrollToBottom={scrollToBottom}/></div></>);};export default ProjectChat;14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565714 unmodified lines}const ProjectChat: React.FC<ChatProps> = ({ mediaList }) => {return <div>TO BE FIXED</div>;// const selectedMediaId = useAtomValue(selectedMediaIdAtom);// // fallback to the first media// const selectedMedia =// mediaList.find(media => media.id === selectedMediaId) ?? mediaList[0];// const { messages, append, reload, stop, isLoading, input, setInput } =// useVisionAgent({// mediaUrl: selectedMedia.url,// messages: [],// userId: nanoid(),// });// const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } =// useScrollAnchor();// return (// <>// <div className="h-full overflow-auto" ref={scrollRef}>// <div className="pb-[200px] pt-4 md:pt-10" ref={messagesRef}>// <ChatList messages={messages} session={null} isLoading={isLoading} />// <div className="h-px w-full" ref={visibilityRef} />// </div>// </div>// <div className="absolute inset-x-0 bottom-0 w-full h-[178px]">// <Composer// url={selectedMedia.url}// isLoading={isLoading}// stop={stop}// append={append}// reload={reload}// messages={messages}// input={input}// setInput={setInput}// isAtBottom={isAtBottom}// scrollToBottom={scrollToBottom}// />// </div>// </>// );};export default ProjectChat;
565 unmodified lines566567568569570571572573565 unmodified lines<pathd="M8.4449 0.608765C8.0183 -0.107015 6.9817 -0.107015 6.55509 0.608766L0.161178 11.3368C-0.275824 12.07 0.252503 13 1.10608 13H13.8939C14.7475 13 15.2758 12.07 14.8388 11.3368L8.4449 0.608765ZM7.4141 1.12073C7.45288 1.05566 7.54712 1.05566 7.5859 1.12073L13.9798 11.8488C14.0196 11.9154 13.9715 12 13.8939 12H1.10608C1.02849 12 0.980454 11.9154 1.02018 11.8488L7.4141 1.12073ZM6.8269 4.48611C6.81221 4.10423 7.11783 3.78663 7.5 3.78663C7.88217 3.78663 8.18778 4.10423 8.1731 4.48612L8.01921 8.48701C8.00848 8.766 7.7792 8.98664 7.5 8.98664C7.2208 8.98664 6.99151 8.766 6.98078 8.48701L6.8269 4.48611ZM8.24989 10.476C8.24989 10.8902 7.9141 11.226 7.49989 11.226C7.08567 11.226 6.74989 10.8902 6.74989 10.476C6.74989 10.0618 7.08567 9.72599 7.49989 9.72599C7.9141 9.72599 8.24989 10.0618 8.24989 10.476Z"fill="currentColor"fill-rule="evenodd"clip-rule="evenodd"></path></svg>);565 unmodified lines566567568569570571572573565 unmodified lines<pathd="M8.4449 0.608765C8.0183 -0.107015 6.9817 -0.107015 6.55509 0.608766L0.161178 11.3368C-0.275824 12.07 0.252503 13 1.10608 13H13.8939C14.7475 13 15.2758 12.07 14.8388 11.3368L8.4449 0.608765ZM7.4141 1.12073C7.45288 1.05566 7.54712 1.05566 7.5859 1.12073L13.9798 11.8488C14.0196 11.9154 13.9715 12 13.8939 12H1.10608C1.02849 12 0.980454 11.9154 1.02018 11.8488L7.4141 1.12073ZM6.8269 4.48611C6.81221 4.10423 7.11783 3.78663 7.5 3.78663C7.88217 3.78663 8.18778 4.10423 8.1731 4.48612L8.01921 8.48701C8.00848 8.766 7.7792 8.98664 7.5 8.98664C7.2208 8.98664 6.99151 8.766 6.98078 8.48701L6.8269 4.48611ZM8.24989 10.476C8.24989 10.8902 7.9141 11.226 7.49989 11.226C7.08567 11.226 6.74989 10.8902 6.74989 10.476C6.74989 10.0618 7.08567 9.72599 7.49989 9.72599C7.9141 9.72599 8.24989 10.0618 8.24989 10.476Z"fill="currentColor"fillRule="evenodd"clipRule="evenodd"></path></svg>);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145'use server';
import { sessionUser } from '@/auth';import prisma from './prisma';import { ChatWithMessages, MessageRaw } from './types';
/** * Finds or creates a user in the database based on the provided email and name. * If the user already exists, it returns the existing user. * If the user doesn't exist, it creates a new user and returns it. * * @param email - The email of the user. * @param name - The name of the user. * @returns A promise that resolves to the user object. */export async function dbFindOrCreateUser(email: string, name: string) { // Try to find the user by email const user = await prisma.user.findUnique({ where: { email: email }, });
// If the user doesn't exist, create it if (user) { return user; } else { return prisma.user.create({ data: { email: email, name: name, }, }); }}
/** * Retrieves all chats with their associated messages for the current user. * @returns A promise that resolves to an array of `ChatWithMessages` objects. */export async function dbGetAllChat(): Promise<ChatWithMessages[]> { const { id: userId } = await sessionUser();
if (!userId) return [];
return prisma.chat.findMany({ where: { userId }, include: { messages: true, }, });}
/** * Retrieves a chat with messages from the database based on the provided ID. * @param id - The ID of the chat to retrieve. * @returns A Promise that resolves to a ChatWithMessages object if found, or null if not found. */export async function dbGetChat(id: string): Promise<ChatWithMessages | null> { return prisma.chat.findUnique({ where: { id }, include: { messages: true, }, });}
/** * Creates a new chat in the database. * * @param {string} options.id - The ID of the chat (optional). * @param {string} options.mediaUrl - The media URL for the chat. * @param {MessageRaw[]} options.initMessages - The initial messages for the chat (optional). * @returns {Promise<Chat>} The created chat object. */export async function dbPostCreateChat({ id, mediaUrl, initMessages = [],}: { id?: string; mediaUrl: string; initMessages?: MessageRaw[];}) { const { id: userId } = await sessionUser(); const userConnect = userId ? { user: { connect: { id: userId }, // Connect the chat to an existing user }, } : {}; try { return await prisma.chat.create({ data: { id, mediaUrl: mediaUrl, ...userConnect, messages: { create: initMessages.map(message => ({ ...message, ...userConnect, })), }, }, include: { messages: true, }, }); } catch (error) { console.error(error); }}
/** * Creates a new message in the database. * @param chatId - The ID of the chat where the message belongs. * @param message - The message object to be created. * @returns A promise that resolves to the created message. */export async function dbPostCreateMessage(chatId: string, message: MessageRaw) { const { id: userId } = await sessionUser(); const userConnect = userId ? { user: { connect: { id: userId }, // Connect the chat to an existing user }, } : {};
return prisma.message.create({ data: { content: message.content, role: message.role, chat: { connect: { id: chatId }, }, ...userConnect, }, });}
export async function dbDeleteChat(chatId: string) { return prisma.chat.delete({ where: { id: chatId }, });}12345import { PrismaClient } from '@prisma/client';
const prisma: PrismaClient = new PrismaClient();
export default prisma;12345678import { Chat, Message } from '@prisma/client';
export type ChatWithMessages = Chat & { messages: Message[] };
export type MessageRaw = { role: Message['role']; content: Message['content'];};123456782 unmodified lines11121314151633 unmodified lines505152535455565743 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321334 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165import { useChat, type Message, UseChatHelpers } from 'ai/react';import { toast } from 'react-hot-toast';import { useEffect, useState } from 'react';import { ChatEntity, MessageBase, SignedPayload } from '../types';import { saveKVChatMessage } from '../kv/chat';import { fetcher, nanoid } from '../utils';import {getCleanedUpMessages,2 unmodified lines} from '../messageUtils';import { CLEANED_SEPARATOR } from '../constants';import { useSearchParams } from 'next/navigation';const uploadBase64 = async (base64: string,33 unmodified lines}};const useVisionAgent = (chat: ChatEntity) => {const { messages: initialMessages, id, url } = chat;const searchParams = useSearchParams();const reflectionValue = searchParams.get('reflection');43 unmodified lines{id: nanoid(),role: 'user',content: input + '\n\n' + generateInputImageMarkdown(url),createdAt: new Date(),} satisfies Message,]: []),newMessage,]);if (id) {saveKVChatMessage(id, newMessage);}} else {if (id) {saveKVChatMessage(id, {...message,content: logs + CLEANED_SEPARATOR + content,});}}},initialMessages: initialMessages,body: {url,id,enableSelfReflection: reflectionValue === 'true',},});useEffect(() => {if (!isLoading &&4 unmodified lines}}, [isLoading, messages, reload]);const assistantLoadingMessage = {id: 'loading',content: '...',role: 'assistant',};const messageWithLoading =isLoading &&messages.length &&messages[messages.length - 1].role !== 'assistant'? [...messages, assistantLoadingMessage]: messages;const append: UseChatHelpers['append'] = async message => {if (id) {await saveKVChatMessage(id, message as MessageBase);}return appendRaw(message);};return {messages: messageWithLoading as MessageBase[],append,reload,stop,12345672 unmodified lines101112131415161733 unmodified lines515253545556575843 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391404 unmodified lines145146147148149150151152153154155156157158159160import { useChat, type Message, UseChatHelpers } from 'ai/react';import { toast } from 'react-hot-toast';import { useEffect, useState } from 'react';import { MessageBase, SignedPayload } from '../types';import { fetcher, nanoid } from '../utils';import {getCleanedUpMessages,2 unmodified lines} from '../messageUtils';import { CLEANED_SEPARATOR } from '../constants';import { useSearchParams } from 'next/navigation';import { ChatWithMessages, MessageRaw } from '../db/types';import { dbPostCreateMessage } from '../db/functions';const uploadBase64 = async (base64: string,33 unmodified lines}};const useVisionAgent = (chat: ChatWithMessages) => {const { messages: initialMessages, id, mediaUrl } = chat;const searchParams = useSearchParams();const reflectionValue = searchParams.get('reflection');43 unmodified lines{id: nanoid(),role: 'user',content:input + '\n\n' + generateInputImageMarkdown(mediaUrl),createdAt: new Date(),} satisfies Message,]: []),newMessage,]);await dbPostCreateMessage(id, {role: newMessage.role as 'user' | 'assistant',content: newMessage.content,});} else {await dbPostCreateMessage(id, {role: message.role as 'user' | 'assistant',content: logs + CLEANED_SEPARATOR + content,});}},initialMessages: initialMessages,body: {mediaUrl,id,enableSelfReflection: reflectionValue === 'true',},});/*** If the last message is from the user, reload the chat, this would trigger to get the response from the assistant* There are 2 scenarios when this might happen* 1. Navigated from example images, init message only include preset user message* 2. Last time the assistant message failed or not saved to database.*/useEffect(() => {if (!isLoading &&4 unmodified lines}}, [isLoading, messages, reload]);const append: UseChatHelpers['append'] = async message => {dbPostCreateMessage(id, {role: message.role as 'user' | 'assistant',content: message.content,});return appendRaw(message);};return {messages: messages as MessageBase[],append,reload,stop,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118'use server';import { revalidatePath } from 'next/cache';import { kv } from '@vercel/kv';import { auth, authEmail } from '@/auth';import { ChatEntity, MessageBase } from '@/lib/types';import { notFound, redirect } from 'next/navigation';import { nanoid } from '../utils';export async function getKVChats() {const { email } = await authEmail();try {const pipeline = kv.pipeline();const chats: string[] = await kv.zrange(`user:chat:${email}`, 0, -1, {rev: true,});for (const chat of chats) {pipeline.hgetall(chat);}const results = (await pipeline.exec()) as ChatEntity[];return results.filter(r => !!r).sort((r1, r2) => r2.updatedAt - r1.updatedAt);} catch (error) {console.error('getKVChats error:', error);return [];}}export async function adminGetAllKVChats() {const { isAdmin } = await authEmail();if (!isAdmin) {notFound();}try {const pipeline = kv.pipeline();const chats: string[] = await kv.zrange(`user:chat:all`, 0, -1, {rev: true,});for (const chat of chats) {pipeline.hgetall(chat);}const results = (await pipeline.exec()) as ChatEntity[];return results.sort((r1, r2) => r2.updatedAt - r1.updatedAt);} catch (error) {return [];}}export async function getKVChat(id: string) {// const { email, isAdmin } = await authEmail();const chat = await kv.hgetall<ChatEntity>(`chat:${id}`);if (!chat) {redirect('/');}return chat;}export async function createKVChat(chat: ChatEntity) {// const { email, isAdmin } = await authEmail();const { email } = await authEmail();await kv.hmset(`chat:${chat.id}`, chat);if (email) {await kv.zadd(`user:chat:${email}`, {score: Date.now(),member: `chat:${chat.id}`,});}await kv.zadd('user:chat:all', {score: Date.now(),member: `chat:${chat.id}`,});revalidatePath('/chat', 'layout');}export async function saveKVChatMessage(id: string, message: MessageBase) {const chat = await kv.hgetall<ChatEntity>(`chat:${id}`);if (!chat) {notFound();}const { messages } = chat;await kv.hmset(`chat:${id}`, {...chat,messages: [...messages, message],updatedAt: Date.now(),});return revalidatePath('/chat', 'layout');}export async function removeKVChat(id: string) {const { email } = await authEmail();if (!email) {return {error: 'Unauthorized',};}await Promise.all([kv.zrem(`user:chat:${email}`, `chat:${id}`),kv.del(`chat:${id}`),]);return revalidatePath('/chat', 'layout');}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// 'use server';// import { revalidatePath } from 'next/cache';// import { kv } from '@vercel/kv';// import { auth, sessionUser } from '@/auth';// import { ChatEntity, MessageBase } from '@/lib/types';// import { notFound, redirect } from 'next/navigation';// import { nanoid } from '../utils';// export async function getKVChats() {// const { email } = await sessionUser();// try {// const pipeline = kv.pipeline();// const chats: string[] = await kv.zrange(`user:chat:${email}`, 0, -1, {// rev: true,// });// for (const chat of chats) {// pipeline.hgetall(chat);// }// const results = (await pipeline.exec()) as ChatEntity[];// return results// .filter(r => !!r)// .sort((r1, r2) => r2.updatedAt - r1.updatedAt);// } catch (error) {// console.error('getKVChats error:', error);// return [];// }// }// export async function adminGetAllKVChats() {// const { isAdmin } = await sessionUser();// if (!isAdmin) {// notFound();// }// try {// const pipeline = kv.pipeline();// const chats: string[] = await kv.zrange(`user:chat:all`, 0, -1, {// rev: true,// });// for (const chat of chats) {// pipeline.hgetall(chat);// }// const results = (await pipeline.exec()) as ChatEntity[];// return results.sort((r1, r2) => r2.updatedAt - r1.updatedAt);// } catch (error) {// return [];// }// }// export async function getKVChat(id: string) {// // const { email, isAdmin } = await sessionUser();// const chat = await kv.hgetall<ChatEntity>(`chat:${id}`);// if (!chat) {// redirect('/');// }// return chat;// }// export async function createKVChat(chat: ChatEntity) {// // const { email, isAdmin } = await sessionUser();// const { email } = await sessionUser();// await kv.hmset(`chat:${chat.id}`, chat);// if (email) {// await kv.zadd(`user:chat:${email}`, {// score: Date.now(),// member: `chat:${chat.id}`,// });// }// await kv.zadd('user:chat:all', {// score: Date.now(),// member: `chat:${chat.id}`,// });// revalidatePath('/chat', 'layout');// }// export async function saveKVChatMessage(id: string, message: MessageBase) {// const chat = await kv.hgetall<ChatEntity>(`chat:${id}`);// if (!chat) {// notFound();// }// const { messages } = chat;// await kv.hmset(`chat:${id}`, {// ...chat,// messages: [...messages, message],// updatedAt: Date.now(),// });// return revalidatePath('/chat', 'layout');// }// export async function removeKVChat(id: string) {// const { email } = await sessionUser();// if (!email) {// return {// error: 'Unauthorized',// };// }// await Promise.all([// kv.zrem(`user:chat:${email}`, `chat:${id}`),// kv.del(`chat:${id}`),// ]);// return revalidatePath('/chat', 'layout');// }
1 unmodified line2345678 unmodified lines16171819202119 unmodified lines41424344454630 unmodified lines77787980811 unmodified line"private": true,"scripts": {"preinstall": "npx only-allow pnpm","dev": "next dev --turbo","build": "next build","start": "next start",8 unmodified lines"@aws-sdk/client-s3": "^3.556.0","@aws-sdk/credential-providers": "^3.556.0","@aws-sdk/s3-presigned-post": "^3.556.0","@radix-ui/react-dropdown-menu": "^2.0.6","@radix-ui/react-label": "^2.0.2","@radix-ui/react-select": "^2.0.0",19 unmodified lines"openai": "^4.24.7","pino": "^9.0.0","pino-loki": "^2.2.1","react": "^18.2.0","react-dom": "^18.2.0","react-dropzone": "^14.2.3",30 unmodified lines"tailwindcss-animate": "^1.0.7","typescript": "^5.3.3"},"packageManager": "pnpm@9.0.4"}1 unmodified line23456788 unmodified lines1718192021222319 unmodified lines4344454647484930 unmodified lines80818283841 unmodified line"private": true,"scripts": {"preinstall": "npx only-allow pnpm","postinstall": "prisma generate","dev": "next dev --turbo","build": "next build","start": "next start",8 unmodified lines"@aws-sdk/client-s3": "^3.556.0","@aws-sdk/credential-providers": "^3.556.0","@aws-sdk/s3-presigned-post": "^3.556.0","@prisma/client": "5.14.0","@radix-ui/react-dropdown-menu": "^2.0.6","@radix-ui/react-label": "^2.0.2","@radix-ui/react-select": "^2.0.0",19 unmodified lines"openai": "^4.24.7","pino": "^9.0.0","pino-loki": "^2.2.1","prisma": "^5.14.0","react": "^18.2.0","react-dom": "^18.2.0","react-dropzone": "^14.2.3",30 unmodified lines"tailwindcss-animate": "^1.0.7","typescript": "^5.3.3"},"packageManager": "pnpm@9.1.1"}
16 unmodified lines17181920212269 unmodified lines929394959697598 unmodified lines6966976986997007012314 unmodified lines3016301730183019302030211540 unmodified lines4562456345644565456645672794 unmodified lines73627363736473657366736716 unmodified lines'@aws-sdk/s3-presigned-post':specifier: ^3.556.0version: 3.556.0'@radix-ui/react-dropdown-menu':specifier: ^2.0.6version: 2.0.6(@types/react-dom@18.2.25)(@types/react@18.2.79)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)69 unmodified linespino-loki:specifier: ^2.2.1version: 2.2.1react:specifier: ^18.2.0version: 18.2.0598 unmodified linesresolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}engines: {node: '>=14'}'@radix-ui/number@1.0.1':resolution: {integrity: sha512-T5gIdVO2mmPW3NNhjNgEP3cqMXjXL9UbO0BzWcXfvdBs+BohbQxvd/K5hSVKmn9/lbTdsQVKbUcP5WLCwvUbBg==}2314 unmodified linespretty-format@3.8.0:resolution: {integrity: sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==}prismjs@1.27.0:resolution: {integrity: sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA==}engines: {node: '>=6'}1540 unmodified lines'@pkgjs/parseargs@0.11.0':optional: true'@radix-ui/number@1.0.1':dependencies:'@babel/runtime': 7.24.42794 unmodified linespretty-format@3.8.0: {}prismjs@1.27.0: {}prismjs@1.29.0: {}16 unmodified lines17181920212223242569 unmodified lines9596979899100101102103598 unmodified lines7027037047057067077087097107117127137147157167177187197207217227237247257267277287297307312314 unmodified lines304630473048304930503051305230533054305530561540 unmodified lines45974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646272794 unmodified lines742274237424742574267427742874297430743116 unmodified lines'@aws-sdk/s3-presigned-post':specifier: ^3.556.0version: 3.556.0'@prisma/client':specifier: 5.14.0version: 5.14.0(prisma@5.14.0)'@radix-ui/react-dropdown-menu':specifier: ^2.0.6version: 2.0.6(@types/react-dom@18.2.25)(@types/react@18.2.79)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)69 unmodified linespino-loki:specifier: ^2.2.1version: 2.2.1prisma:specifier: ^5.14.0version: 5.14.0react:specifier: ^18.2.0version: 18.2.0598 unmodified linesresolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}engines: {node: '>=14'}'@prisma/client@5.14.0':resolution: {integrity: sha512-akMSuyvLKeoU4LeyBAUdThP/uhVP3GuLygFE3MlYzaCb3/J8SfsYBE5PkaFuLuVpLyA6sFoW+16z/aPhNAESqg==}engines: {node: '>=16.13'}peerDependencies:prisma: '*'peerDependenciesMeta:prisma:optional: true'@prisma/debug@5.14.0':resolution: {integrity: sha512-iq56qBZuFfX3fCxoxT8gBX33lQzomBU0qIUaEj1RebsKVz1ob/BVH1XSBwwwvRVtZEV1b7Fxx2eVu34Ge/mg3w==}'@prisma/engines-version@5.14.0-25.e9771e62de70f79a5e1c604a2d7c8e2a0a874b48':resolution: {integrity: sha512-ip6pNkRo1UxWv+6toxNcYvItNYaqQjXdFNGJ+Nuk2eYtRoEdoF13wxo7/jsClJFFenMPVNVqXQDV0oveXnR1cA==}'@prisma/engines@5.14.0':resolution: {integrity: sha512-lgxkKZ6IEygVcw6IZZUlPIfLQ9hjSYAtHjZ5r64sCLDgVzsPFCi2XBBJgzPMkOQ5RHzUD4E/dVdpn9+ez8tk1A==}'@prisma/fetch-engine@5.14.0':resolution: {integrity: sha512-VrheA9y9DMURK5vu8OJoOgQpxOhas3qF0IBHJ8G/0X44k82kc8E0w98HCn2nhnbOOMwbWsJWXfLC2/F8n5u0gQ==}'@prisma/get-platform@5.14.0':resolution: {integrity: sha512-/yAyBvcEjRv41ynZrhdrPtHgk47xLRRq/o5eWGcUpBJ1YrUZTYB8EoPiopnP7iQrMATK8stXQdPOoVlrzuTQZw==}'@radix-ui/number@1.0.1':resolution: {integrity: sha512-T5gIdVO2mmPW3NNhjNgEP3cqMXjXL9UbO0BzWcXfvdBs+BohbQxvd/K5hSVKmn9/lbTdsQVKbUcP5WLCwvUbBg==}2314 unmodified linespretty-format@3.8.0:resolution: {integrity: sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==}prisma@5.14.0:resolution: {integrity: sha512-gCNZco7y5XtjrnQYeDJTiVZmT/ncqCr5RY1/Cf8X2wgLRmyh9ayPAGBNziI4qEE4S6SxCH5omQLVo9lmURaJ/Q==}engines: {node: '>=16.13'}hasBin: trueprismjs@1.27.0:resolution: {integrity: sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA==}engines: {node: '>=6'}1540 unmodified lines'@pkgjs/parseargs@0.11.0':optional: true'@prisma/client@5.14.0(prisma@5.14.0)':optionalDependencies:prisma: 5.14.0'@prisma/debug@5.14.0': {}'@prisma/engines-version@5.14.0-25.e9771e62de70f79a5e1c604a2d7c8e2a0a874b48': {}'@prisma/engines@5.14.0':dependencies:'@prisma/debug': 5.14.0'@prisma/engines-version': 5.14.0-25.e9771e62de70f79a5e1c604a2d7c8e2a0a874b48'@prisma/fetch-engine': 5.14.0'@prisma/get-platform': 5.14.0'@prisma/fetch-engine@5.14.0':dependencies:'@prisma/debug': 5.14.0'@prisma/engines-version': 5.14.0-25.e9771e62de70f79a5e1c604a2d7c8e2a0a874b48'@prisma/get-platform': 5.14.0'@prisma/get-platform@5.14.0':dependencies:'@prisma/debug': 5.14.0'@radix-ui/number@1.0.1':dependencies:'@babel/runtime': 7.24.42794 unmodified linespretty-format@3.8.0: {}prisma@5.14.0:dependencies:'@prisma/engines': 5.14.0prismjs@1.27.0: {}prismjs@1.29.0: {}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859// This is your Prisma schema file,// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client { provider = "prisma-client-js"}
datasource db { provider = "postgresql" url = env("POSTGRES_PRISMA_URL") // uses connection pooling directUrl = env("POSTGRES_URL_NON_POOLING") // uses a direct connection}
model User { id String @id @default(cuid()) name String email String @unique createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @updatedAt @map(name: "updated_at") chats Chat[] message Message[]
@@map("user")}
model Chat { id String @id @default(cuid()) mediaUrl String createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @updatedAt @map(name: "updated_at") user User? @relation(fields: [userId], references: [id]) userId String? messages Message[]
@@map("chat")}
model Message { id String @id @default(cuid()) role MessageRole content String createdAt DateTime @default(now()) @map(name: "created_at") updatedAt DateTime @updatedAt @map(name: "updated_at") user User? @relation(fields: [userId], references: [id]) userId String? chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) chatId String
@@map("message")}
enum MessageRole { system user assistant}app/all/chat/[id]/page.tsx+7-5
app/all/layout.tsx+26-26
app/api/auth/[...nextauth]/route.ts+1-1
app/api/upload/route.ts → app/api/chat/create/route.tsRenamed+11-26
app/api/vision-agent/route.ts+3-3
app/chat/[id]/page.tsx+6-3
app/chat/layout.tsx+4-4
app/chat/page.tsx+8-6
app/project/layout.tsx+2-2
auth.ts+31-13
components/Header.tsx+4-4
components/chat-sidebar/ChatCard.tsx+7-8
components/chat-sidebar/ChatListSidebar.tsx+2-2
components/chat/ImageSelector.tsx+3-2
components/chat/index.tsx+4-4
components/project/ProjectChat.tsx+37-39
components/ui/Icons.tsx+2-2
lib/db/functions.tsAdded+145
lib/db/prisma.tsAdded+5
lib/db/types.tsAdded+8
lib/hooks/useVisionAgent.ts+27-32
lib/kv/chat.ts+118-118
package.json+5-2
pnpm-lock.yaml+64
prisma/schema.prismaAdded+59