Repository: nphivu414/ai-fusion-kit Branch: main Commit: 087ab1c7d7f2 Files: 190 Total size: 329.0 KB Directory structure: gitextract_6e60vi3g/ ├── .eslintrc.json ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .prettierignore ├── LICENSE ├── README.md ├── app/ │ ├── (auth)/ │ │ ├── auth-code-error/ │ │ │ └── page.tsx │ │ ├── layout.tsx │ │ ├── signin/ │ │ │ └── page.tsx │ │ └── signup/ │ │ └── page.tsx │ ├── api/ │ │ ├── auth/ │ │ │ ├── callback/ │ │ │ │ └── route.ts │ │ │ └── logout/ │ │ │ └── route.ts │ │ └── chat/ │ │ └── route.ts │ ├── apps/ │ │ ├── chat/ │ │ │ ├── [id]/ │ │ │ │ └── page.tsx │ │ │ ├── loading.tsx │ │ │ └── page.tsx │ │ ├── layout.tsx │ │ └── page.tsx │ ├── docs/ │ │ └── page.tsx │ ├── globals.css │ ├── layout.tsx │ ├── page.tsx │ ├── profile/ │ │ ├── layout.tsx │ │ └── page.tsx │ └── styles/ │ └── custom.css ├── components/ │ ├── modules/ │ │ ├── apps/ │ │ │ ├── app-side-bar/ │ │ │ │ ├── AppSideBar.tsx │ │ │ │ ├── AppSideBarItem.tsx │ │ │ │ ├── AppSideBarList.tsx │ │ │ │ ├── AppSidebarSection.tsx │ │ │ │ └── index.ts │ │ │ └── chat/ │ │ │ ├── ChatForm.tsx │ │ │ ├── ChatHistory.tsx │ │ │ ├── ChatHistoryDrawer.tsx │ │ │ ├── ChatHistoryItem.tsx │ │ │ ├── ChatLayout.tsx │ │ │ ├── ChatPanel.tsx │ │ │ ├── CodeBlock.tsx │ │ │ ├── DeleteChatAction.tsx │ │ │ ├── EditChatAction.tsx │ │ │ ├── Header.tsx │ │ │ ├── MobileDrawerControls.tsx │ │ │ ├── NewChatButton.tsx │ │ │ ├── SystemPromptControl.tsx │ │ │ ├── action.ts │ │ │ ├── chat-members/ │ │ │ │ ├── AddMembersForm.tsx │ │ │ │ ├── ChatMemberItem.tsx │ │ │ │ ├── ChatMembers.tsx │ │ │ │ ├── DeleteMemberAction.tsx │ │ │ │ ├── action.ts │ │ │ │ ├── index.ts │ │ │ │ └── schema.ts │ │ │ ├── control-side-bar/ │ │ │ │ ├── ControlSidebar.tsx │ │ │ │ ├── ControlSidebarSheet.tsx │ │ │ │ ├── FrequencyPenaltySelector.tsx │ │ │ │ ├── MaxLengthSelector.tsx │ │ │ │ ├── ModelSelector.tsx │ │ │ │ ├── PresencePenaltySelector.tsx │ │ │ │ ├── TemperatureSelector.tsx │ │ │ │ ├── TopPSelector.tsx │ │ │ │ ├── action.ts │ │ │ │ ├── data/ │ │ │ │ │ └── models.ts │ │ │ │ └── index.ts │ │ │ ├── schema.ts │ │ │ ├── types.ts │ │ │ └── utils.ts │ │ ├── auth/ │ │ │ ├── LogoutButton.tsx │ │ │ ├── SocialLoginButton.tsx │ │ │ ├── SocialLoginOptions.tsx │ │ │ ├── UserAuthForm.tsx │ │ │ ├── UserSignupForm.tsx │ │ │ └── schema.ts │ │ ├── home/ │ │ │ ├── DescriptionHeadingText.tsx │ │ │ ├── FeatureItems.tsx │ │ │ └── HeroBannerImage.tsx │ │ └── profile/ │ │ ├── AccountDropdownMenu.tsx │ │ ├── Header.tsx │ │ ├── ProfileForm.tsx │ │ ├── action.ts │ │ ├── schema.ts │ │ └── type.ts │ ├── navigation/ │ │ ├── NavigationBar.tsx │ │ ├── NavigationMainMenu.tsx │ │ └── SideBar.tsx │ ├── theme/ │ │ ├── ThemeToggle.tsx │ │ └── index.ts │ └── ui/ │ ├── Accordion.tsx │ ├── AlertDialog.tsx │ ├── Avatar.tsx │ ├── Badge.tsx │ ├── Button.tsx │ ├── Card.tsx │ ├── Command.tsx │ ├── CustomIcon.tsx │ ├── Dialog.tsx │ ├── DropdownMenu.tsx │ ├── Flex.tsx │ ├── HoverCard.tsx │ ├── Input.tsx │ ├── Label.tsx │ ├── NavigationMenu.tsx │ ├── Popover.tsx │ ├── Resizable.tsx │ ├── ScrollArea.tsx │ ├── Section.tsx │ ├── Select.tsx │ ├── Separator.tsx │ ├── Sheet.tsx │ ├── Skeleton.tsx │ ├── Slider.tsx │ ├── Switch.tsx │ ├── Tabs.tsx │ ├── TextArea.tsx │ ├── Toast.tsx │ ├── Toaster.tsx │ ├── Tooltip.tsx │ ├── chat/ │ │ ├── ChatBubble.tsx │ │ ├── ChatInput.tsx │ │ ├── ChatList.tsx │ │ ├── ChatProfileHoverCard.tsx │ │ ├── Markdown.tsx │ │ ├── index.ts │ │ └── mention-input-default-style.ts │ ├── common/ │ │ ├── AppLogo.tsx │ │ ├── ChatScrollAnchor.tsx │ │ ├── MainLayout.tsx │ │ └── UserAvatar.tsx │ ├── form/ │ │ └── form-fields/ │ │ ├── InputField/ │ │ │ ├── InputField.tsx │ │ │ └── index.ts │ │ ├── SliderField/ │ │ │ ├── SliderField.tsx │ │ │ └── index.ts │ │ ├── TextAreaField/ │ │ │ ├── TextAreaField.tsx │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types.ts │ ├── typography/ │ │ ├── Blockquote.tsx │ │ ├── Heading1.tsx │ │ ├── Heading2.tsx │ │ ├── Heading3.tsx │ │ ├── Heading4.tsx │ │ ├── Heading5.tsx │ │ ├── Paragraph.tsx │ │ ├── Subtle.tsx │ │ ├── index.ts │ │ └── types.ts │ └── use-toast.ts ├── components.json ├── config/ │ └── site.ts ├── env.mjs ├── hooks/ │ ├── useActiveTheme.tsx │ ├── useAtBottom.tsx │ ├── useChatIdFromPathName.tsx │ ├── useCopyToClipboard.tsx │ ├── useEnterSubmit.tsx │ ├── useMutationObserver.ts │ ├── usePrevious.tsx │ └── useSubscribeChatMessages.ts ├── lib/ │ ├── cache.ts │ ├── chat-input.ts │ ├── contants.ts │ ├── db/ │ │ ├── apps.ts │ │ ├── chat-members.ts │ │ ├── chats.ts │ │ ├── database.types.ts │ │ ├── index.ts │ │ ├── message.ts │ │ └── profile.ts │ ├── session.ts │ ├── stores/ │ │ └── profile.ts │ ├── supabase/ │ │ ├── client.ts │ │ ├── middleware.ts │ │ └── server.ts │ └── utils.ts ├── middleware.ts ├── next.config.js ├── package.json ├── postcss.config.js ├── prettier.config.js ├── supabase/ │ ├── .gitignore │ ├── config.toml │ ├── migrations/ │ │ ├── 20240402103717_init_schema.sql │ │ ├── 20240403013936_rls.sql │ │ ├── 20240405151156_default_profile_id.sql │ │ ├── 20240420162835_chat_members.sql │ │ ├── 20240504083818_chat_members.sql │ │ ├── 20240609070425_handle_new_user_update.sql │ │ ├── 20240626065103_migrate_username_from_email.sql │ │ └── 20240626065226_update_handle_new_user.sql │ └── seed.sql ├── tailwind.config.js └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintrc.json ================================================ { "$schema": "https://json.schemastore.org/eslintrc", "root": true, "extends": [ "next/core-web-vitals", "plugin:tailwindcss/recommended", "plugin:@typescript-eslint/recommended", "prettier" ], "plugins": ["tailwindcss", "prettier"], "rules": { "@next/next/no-html-link-for-pages": "off", "react/jsx-key": "off", "tailwindcss/no-custom-classname": "off", "@typescript-eslint/no-unused-vars": "error", "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/no-empty-function": "off", "prettier/prettier": "error" }, "settings": { "tailwindcss": { "callees": ["cn"], "config": "tailwind.config.js" }, "next": { "rootDir": ["./"] } }, "overrides": [ { "files": ["*.ts", "*.tsx"], "parser": "@typescript-eslint/parser" } ] } ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [nphivu414] ================================================ FILE: .gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # local env files .env.* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts .env ================================================ FILE: .prettierignore ================================================ cache .cache package.json package-lock.json public CHANGELOG.md .yarn dist node_modules .next build .contentlayer ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2023 Vu Nguyen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ AI Fusion Kit

AI Fusion Kit

A feature-rich, highly customizable AI Web App Template, empowered by Next.js.

Tech stacks · Installation · Run Locally · Authors


## Tech stacks - [Typescript](https://www.typescriptlang.org/) - [ReactJS](https://reactjs.org/) - [NextJS](https://nextjs.org/) - [Supabase](https://supabase.com/) - [Open AI API](https://platform.openai.com/docs/api-reference) - [Vercel AI SDK](https://github.com/vercel/ai) - [TailwindCSS](https://tailwindcss.com/) - [Shadcn UI](https://ui.shadcn.com/) - [Aceternity UI](https://ui.aceternity.com/) - [Next.js AI Chatbot](https://github.com/vercel-labs/ai-chatbot) ## Installation 1. Clone the repo ```sh git clone https://github.com/nphivu414/ai-fusion-kit ``` 2. Install dependencies ```sh yarn install ``` 3. Setup Supabase local development - Install [Docker](https://www.docker.com/get-started/) - The start command uses Docker to start the Supabase services. This command may take a while to run if this is the first time using the CLI. ```sh supabase start ``` - Once all of the Supabase services are running, you'll see output containing your local Supabase credentials. It should look like this, with urls and keys that you'll use in your local project: ```sh Started supabase local development setup. API URL: http://localhost:54321 DB URL: postgresql://postgres:postgres@localhost:54322/postgres Studio URL: http://localhost:54323 Inbucket URL: http://localhost:54324 anon key: eyJh...... service_role key: eyJh...... ``` - The API URL will be used as the `NEXT_PUBLIC_SUPABASE_URL` in `.env.local` - For more information about how to use Supabase on your local development machine: https://supabase.com/docs/guides/cli/local-development 4. Get an account from OpenAI and generate your own API key 5. Rename `.env.example` to `.env.local` and populate with your values > Note: You should not commit your `.env` file or it will expose secrets that will allow others to control access to your various OpenAI and authentication provider accounts. ## Run Locally 1. Go to the project directory ```bash cd ai-fusion-kit ``` 2. Start the web app ```bash yarn dev ``` ## Authors - [@nphivu414](https://github.com/nphivu414) - [@toproad1407](https://github.com/toproad1407) ================================================ FILE: app/(auth)/auth-code-error/page.tsx ================================================ import { Metadata } from "next"; import { Heading3 } from "@/components/ui/typography/Heading3"; export const metadata: Metadata = { title: "Error", description: "Failed to sign in", }; export default async function AuthCodeError() { return ( <>
Error

Failed to sign in

); } ================================================ FILE: app/(auth)/layout.tsx ================================================ import { AppLogo } from "@/components/ui/common/AppLogo"; type AuthLayoutProps = { children: React.ReactNode; }; export default function AuthLayout({ children }: AuthLayoutProps) { return (
{children}
); } ================================================ FILE: app/(auth)/signin/page.tsx ================================================ import { Metadata } from "next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { siteConfig } from "@/config/site"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { Heading3 } from "@/components/ui/typography"; import { UserAuthForm } from "@/components/modules/auth/UserAuthForm"; export const metadata: Metadata = { title: "Sigin", description: "Sigin to your account", }; export const runtime = "edge"; export const dynamic = "force-dynamic"; export default async function LoginPage() { const cookieStore = cookies(); const supabase = createClient(cookieStore); const user = await getCurrentUser(supabase); if (user) { redirect(`/apps/chat`); } return ( <>
{siteConfig.name}

Empowering Your Imagination with AI Services

); } ================================================ FILE: app/(auth)/signup/page.tsx ================================================ import { Metadata } from "next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { siteConfig } from "@/config/site"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { Heading3 } from "@/components/ui/typography"; import { UserSignupForm } from "@/components/modules/auth/UserSignupForm"; export const runtime = "edge"; export const metadata: Metadata = { title: "Signup", description: "Signup a new account", }; export const dynamic = "force-dynamic"; export default async function LoginPage() { const cookieStore = cookies(); const supabase = createClient(cookieStore); const user = await getCurrentUser(supabase); if (user) { redirect(`/apps/chat`); } return ( <>
{siteConfig.name}

Empowering Your Imagination with AI Services

); } ================================================ FILE: app/api/auth/callback/route.ts ================================================ import { cookies } from "next/headers"; import { NextResponse } from "next/server"; import { createClient } from "@/lib/supabase/server"; export async function GET(request: Request) { const { searchParams, origin } = new URL(request.url); const code = searchParams.get("code"); // if "next" is in param, use it as the redirect URL const next = searchParams.get("next") ?? "/"; if (code) { const cookieStore = cookies(); const supabase = createClient(cookieStore); const { error } = await supabase.auth.exchangeCodeForSession(code); if (!error) { return NextResponse.redirect(`${origin}${next}`); } } // return the user to an error page with instructions return NextResponse.redirect(`${origin}/auth-code-error`); } ================================================ FILE: app/api/auth/logout/route.ts ================================================ import { cookies } from "next/headers"; import { NextResponse, type NextRequest } from "next/server"; import { createClient } from "@/lib/supabase/server"; export const dynamic = "force-dynamic"; export async function POST(req: NextRequest) { const cookieStore = cookies(); const supabase = createClient(cookieStore); // Check if we have a session const { data: { user }, } = await supabase.auth.getUser(); if (user) { await supabase.auth.signOut(); } return NextResponse.redirect(new URL("/signin", req.url), { status: 302, }); } ================================================ FILE: app/api/chat/route.ts ================================================ import { cookies } from "next/headers"; import { env } from "@/env.mjs"; import { createOpenAI } from "@ai-sdk/openai"; import { Message, streamText } from "ai"; import { pick } from "lodash"; import { AxiomRequest, withAxiom } from "next-axiom"; import { getAppBySlug } from "@/lib/db/apps"; import { createNewChatMember } from "@/lib/db/chat-members"; import { createNewChat } from "@/lib/db/chats"; import { createNewMessage, deleteMessagesFrom, getMessageById, } from "@/lib/db/message"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; export const dynamic = "force-dynamic"; export const runtime = "edge"; export const preferredRegion = "home"; const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY, }); export const POST = withAxiom(async (req: AxiomRequest) => { const log = req.log.with({ route: "api/chat", }); const cookieStore = cookies(); const supabase = createClient(cookieStore); const params = await req.json(); const { messages, temperature, model, maxTokens, topP, frequencyPenalty, presencePenalty, chatId, isRegenerate, regenerateMessageId, isNewChat, enableChatAssistant = true, } = params; const user = await getCurrentUser(supabase); const currentApp = await getAppBySlug(supabase, "/apps/chat"); if (!user) { return new Response("Unauthorized", { status: 401 }); } const lastMessage = messages[messages.length - 1]; if (!isRegenerate) { if (isNewChat && currentApp) { await createNewChat(supabase, { id: chatId, app_id: currentApp.id, name: lastMessage.content, }); await createNewChatMember(supabase, { chat_id: chatId, member_id: user.id, }); } await createNewMessage(supabase, { chat_id: chatId, content: lastMessage.content, role: "user", id: lastMessage.id, }); } else if (regenerateMessageId) { const fromMessage = await getMessageById(supabase, regenerateMessageId); if (fromMessage?.created_at) { await deleteMessagesFrom(supabase, chatId, fromMessage.created_at); } } if (!enableChatAssistant) { return new Response(null, { status: 200, headers: { "Content-Type": "application/json", "should-redirect-to-new-chat": "true", }, }); } log.debug("Start stream text"); const response = await streamText({ model: openai(model), temperature, messages: messages.map((message: Message) => pick(message, "content", "role") ), maxTokens, topP, frequencyPenalty, presencePenalty, onFinish: async ({ text }) => { await createNewMessage(supabase, { chat_id: chatId, content: text, role: "assistant", }); }, }); log.debug("End stream text"); return response.toAIStreamResponse(); }); ================================================ FILE: app/apps/chat/[id]/page.tsx ================================================ import React from "react"; import { Metadata } from "next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { Message } from "ai"; import { CHAT_MEMBER_SIDEBAR_LAYOUT_COOKIE, DEFAULT_CHAT_MEMBER_SIDEBAR_LAYOUT, } from "@/lib/contants"; import { getAppBySlug } from "@/lib/db/apps"; import { getChatMembers } from "@/lib/db/chat-members"; import { getChatById, getChats } from "@/lib/db/chats"; import { getMessages } from "@/lib/db/message"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { ChatPanel } from "@/components/modules/apps/chat/ChatPanel"; import { ChatParams } from "@/components/modules/apps/chat/types"; export const runtime = "edge"; export const preferredRegion = "home"; export const metadata: Metadata = { title: "Chat", description: "Chat with your AI assistant to generate new ideas and get inspired.", }; export default async function ChatPage({ params }: { params: { id: string } }) { const chatId = params.id; const cookieStore = cookies(); const supabase = createClient(cookieStore); const user = await getCurrentUser(supabase); const currentApp = await getAppBySlug(supabase, "/apps/chat"); if (!currentApp || !user) { return
No app found
; } const chats = await getChats(supabase, currentApp.id); const dbMessages = await getMessages(supabase, chatId); const chatDetails = await getChatById(supabase, chatId); if (!chatDetails) { redirect("/apps/chat"); } const chatParams = chatDetails?.settings as ChatParams | undefined; const isChatHost = chatDetails?.profile_id === user.id; const initialChatMessages: Message[] = dbMessages?.length ? dbMessages.map((message) => { return { id: message.id, role: message.role || "system", content: message.content || "", data: { profile_id: message.profile_id, chat_id: message.chat_id, chatBubleDirection: message.role === "user" && message.profile_id === user.id ? "end" : "start", }, }; }) : []; if (chatParams?.description) { initialChatMessages.unshift({ id: "description", role: "system", content: chatParams.description, }); } const chatMembers = await getChatMembers(supabase, chatId); const memberSidebarLayout = cookies().get(CHAT_MEMBER_SIDEBAR_LAYOUT_COOKIE); let defaultMemberSidebarLayout = DEFAULT_CHAT_MEMBER_SIDEBAR_LAYOUT; if (memberSidebarLayout) { defaultMemberSidebarLayout = JSON.parse(memberSidebarLayout.value); } return ( ); } ================================================ FILE: app/apps/chat/loading.tsx ================================================ import { Loader } from "lucide-react"; import { Separator } from "@/components/ui/Separator"; import { Skeleton } from "@/components/ui/Skeleton"; import { Heading2 } from "@/components/ui/typography"; export default function Page() { return (
GPT AI Assistant
); } ================================================ FILE: app/apps/chat/page.tsx ================================================ import React from "react"; import { Metadata } from "next"; import { cookies } from "next/headers"; import { v4 as uuidv4 } from "uuid"; import { getAppBySlug } from "@/lib/db/apps"; import { getChats } from "@/lib/db/chats"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { ChatPanel } from "@/components/modules/apps/chat/ChatPanel"; export const metadata: Metadata = { title: "Create a New Chat", }; export default async function NewChatPage() { const chatId = uuidv4(); const cookieStore = cookies(); const supabase = createClient(cookieStore); const user = await getCurrentUser(supabase); const currentApp = await getAppBySlug(supabase, "/apps/chat"); if (!currentApp || !user) { return
No app found
; } const chats = await getChats(supabase, currentApp.id); return ( ); } ================================================ FILE: app/apps/layout.tsx ================================================ import { cookies } from "next/headers"; import { getAppBySlug } from "@/lib/db/apps"; import { getChats } from "@/lib/db/chats"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { MainLayout } from "@/components/ui/common/MainLayout"; import { ChatHistory } from "@/components/modules/apps/chat/ChatHistory"; interface AppLayoutProps { children: React.ReactNode; } export default async function AppLayout({ children }: AppLayoutProps) { const cookieStore = cookies(); const supabase = createClient(cookieStore); const user = await getCurrentUser(supabase); const currentApp = await getAppBySlug(supabase, "/apps/chat"); if (!currentApp || !user) { return
No app found
; } const chats = await getChats(supabase, currentApp.id); return (
{children}
); } ================================================ FILE: app/apps/page.tsx ================================================ import { Heading1 } from "@/components/ui/typography"; export const runtime = "edge"; export default function Apps() { return Apps; } ================================================ FILE: app/docs/page.tsx ================================================ export default async function Docs() { return
docs
; } ================================================ FILE: app/globals.css ================================================ @import url('./styles/custom.css'); @tailwind base; @tailwind components; @tailwind utilities; .drawer-toggle:checked ~ .drawer-side { backdrop-filter: blur(5px); } @media screen and (-webkit-min-device-pixel-ratio:0) { select, textarea, input { font-size: 16px !important; } } @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --card: 0 0% 100%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --primary: 262.1 83.3% 57.8%; --primary-foreground: 210 20% 98%; --secondary: 240 4.8% 95.9%; --secondary-foreground: 240 5.9% 10%; --muted: 240 4.8% 95.9%; --muted-foreground: 240 3.8% 46.1%; --accent: 240 4.8% 95.9%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 240 5.9% 90%; --input: 240 5.9% 90%; --ring: 262.1 83.3% 57.8%; --radius: 0.5rem; } .dark { --background: 20 14.3% 4.1%; --foreground: 0 0% 95%; --card: 24 9.8% 10%; --card-foreground: 0 0% 95%; --popover: 0 0% 9%; --popover-foreground: 0 0% 95%; --primary: 263.4 70% 50.4%; --primary-foreground: 210 20% 98%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 0 0% 15%; --muted-foreground: 240 5% 64.9%; --accent: 12 6.5% 15.1%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 85.7% 97.3%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 263.4 70% 50.4%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: app/layout.tsx ================================================ import { AxiomWebVitals } from "next-axiom"; import "./globals.css"; import { Metadata, Viewport } from "next"; import { Analytics } from "@vercel/analytics/react"; import { GeistMono } from "geist/font/mono"; import { GeistSans } from "geist/font/sans"; import { ThemeProvider } from "next-themes"; import { siteConfig } from "@/config/site"; import { Toaster } from "@/components/ui/Toaster"; export const metadata: Metadata = { title: { default: siteConfig.name, template: `%s - ${siteConfig.name}`, }, description: siteConfig.description, icons: { icon: "/favicon.ico", shortcut: "/favicon-16x16.png", apple: "/apple-touch-icon.png", }, }; export const viewport: Viewport = { themeColor: [ { media: "(prefers-color-scheme: light)", color: "white" }, { media: "(prefers-color-scheme: dark)", color: "black" }, ], }; interface RootLayoutProps { children: React.ReactNode; } export default function RootLayout({ children }: RootLayoutProps) { return ( <> {children} ); } ================================================ FILE: app/page.tsx ================================================ import { Metadata } from "next"; import Link from "next/link"; import { Play } from "lucide-react"; import { siteConfig } from "@/config/site"; import { cn } from "@/lib/utils"; import { buttonVariants } from "@/components/ui/Button"; import { MainLayout } from "@/components/ui/common/MainLayout"; import { Heading1 } from "@/components/ui/typography"; import { DescriptionHeadingText } from "@/components/modules/home/DescriptionHeadingText"; import { FeatureItems } from "@/components/modules/home/FeatureItems"; import { HeroBannerImage } from "@/components/modules/home/HeroBannerImage"; export const metadata: Metadata = { title: siteConfig.name, description: siteConfig.description, }; export const runtime = "edge"; export default async function Home() { return (
{siteConfig.name}
Demo Get Started
); } ================================================ FILE: app/profile/layout.tsx ================================================ import { MainLayout } from "@/components/ui/common/MainLayout"; interface AppLayoutProps { children: React.ReactNode; } export default function AppLayout({ children }: AppLayoutProps) { return (
{children}
); } ================================================ FILE: app/profile/page.tsx ================================================ import { cookies } from "next/headers"; import { getCurrentProfile } from "@/lib/db/profile"; import { getCurrentUser } from "@/lib/session"; import { createClient } from "@/lib/supabase/server"; import { Header } from "@/components/modules/profile/Header"; import { ProfileForm } from "@/components/modules/profile/ProfileForm"; import { ProfileFormValues } from "@/components/modules/profile/type"; export const dynamic = "force-dynamic"; export const runtime = "edge"; export default async function Profile() { const cookieStore = cookies(); const supabase = createClient(cookieStore); const profile = await getCurrentProfile(supabase); const user = await getCurrentUser(supabase); if (!profile) { return null; } const { avatar_url, full_name, username, website } = profile; const profileFormValues: ProfileFormValues = { fullName: full_name || undefined, username: username || undefined, website: website || undefined, }; return (
); } ================================================ FILE: app/styles/custom.css ================================================ /* Styles extracted from https://github.com/saadeghi/daisyui */ .avatar { position: relative; display: inline-flex } .avatar>div { display: block; aspect-ratio: 1/1; overflow: hidden } .avatar img { height: 100%; width: 100%; object-fit: cover } .avatar.placeholder>div { display: flex; align-items: center; justify-content: center } .chat { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); column-gap: .75rem; padding-top: .25rem; padding-bottom: .25rem } .chat-image { grid-row: span 2/span 2; align-self: flex-end } .chat-header { grid-row-start: 1; font-size: .875rem; line-height: 1.25rem } .chat-footer { grid-row-start: 3; font-size: .875rem; line-height: 1.25rem } .chat-bubble { position: relative; display: block; width: -moz-fit-content; width: fit-content; padding: .5rem 1rem; max-width: 90%; border-radius: var(--rounded-box,1rem); min-height: 2.75rem; min-width: 2.75rem; --tw-bg-opacity: 1; background-color: var(--fallback-n,oklch(var(--n)/var(--tw-bg-opacity))); --tw-text-opacity: 1; color: var(--fallback-nc,oklch(var(--nc)/var(--tw-text-opacity))) } .chat-bubble:before { position: absolute; bottom: 0; height: .75rem; width: .75rem; background-color: inherit; content: ""; -webkit-mask-size: contain; mask-size: contain; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -webkit-mask-position: center; mask-position: center } .chat-start { place-items: start; grid-template-columns: auto 1fr } .chat-start .chat-header,.chat-start .chat-footer { grid-column-start: 2 } .chat-start .chat-image { grid-column-start: 1 } .chat-start .chat-bubble { grid-column-start: 2; border-end-start-radius: 0 } .chat-start .chat-bubble:before { -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDMgMyBMIDMgMCBDIDMgMSAxIDMgMCAzJy8+PC9zdmc+); mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDMgMyBMIDMgMCBDIDMgMSAxIDMgMCAzJy8+PC9zdmc+); inset-inline-start: -.749rem } [dir=rtl] .chat-start .chat-bubble:before { -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDEgMyBMIDMgMyBDIDIgMyAwIDEgMCAwJy8+PC9zdmc+); mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDEgMyBMIDMgMyBDIDIgMyAwIDEgMCAwJy8+PC9zdmc+) } .chat-end { place-items: end; grid-template-columns: 1fr auto } .chat-end .chat-header,.chat-end .chat-footer { grid-column-start: 1 } .chat-end .chat-image { grid-column-start: 2 } .chat-end .chat-bubble { grid-column-start: 1; border-end-end-radius: 0 } .chat-end .chat-bubble:before { -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDEgMyBMIDMgMyBDIDIgMyAwIDEgMCAwJy8+PC9zdmc+); mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDEgMyBMIDMgMyBDIDIgMyAwIDEgMCAwJy8+PC9zdmc+); inset-inline-start: 99.9% } [dir=rtl] .chat-end .chat-bubble:before { -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDMgMyBMIDMgMCBDIDMgMSAxIDMgMCAzJy8+PC9zdmc+); mask-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nMycgaGVpZ2h0PSczJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPjxwYXRoIGZpbGw9J2JsYWNrJyBkPSdtIDAgMyBMIDMgMyBMIDMgMCBDIDMgMSAxIDMgMCAzJy8+PC9zdmc+) } .drawer { position: relative; display: grid; grid-auto-columns: max-content auto; width: 100% } .drawer-content { grid-column-start: 2; grid-row-start: 1; min-width: 0px } .drawer-side { pointer-events: none; position: fixed; inset-inline-start: 0px; top: 0; grid-column-start: 1; grid-row-start: 1; display: grid; width: 100%; grid-template-columns: repeat(1,minmax(0,1fr)); grid-template-rows: repeat(1,minmax(0,1fr)); align-items: flex-start; justify-items: start; overflow-x: hidden; overflow-y: hidden; overscroll-behavior: contain; height: 100vh; height: 100dvh } .drawer-side>.drawer-overlay { position: sticky; top: 0; place-self: stretch; cursor: pointer; background-color: transparent; transition-property: color,background-color,border-color,text-decoration-color,fill,stroke; transition-timing-function: cubic-bezier(.4,0,.2,1); transition-timing-function: cubic-bezier(0,0,.2,1); transition-duration: .2s } .drawer-side>* { grid-column-start: 1; grid-row-start: 1 } .drawer-side>*:not(.drawer-overlay) { transition-property: transform; transition-timing-function: cubic-bezier(.4,0,.2,1); transition-timing-function: cubic-bezier(0,0,.2,1); transition-duration: .3s; will-change: transform; transform: translate(-100%) } [dir=rtl] .drawer-side>*:not(.drawer-overlay) { transform: translate(100%) } .drawer-toggle { position: fixed; height: 0px; width: 0px; -webkit-appearance: none; -moz-appearance: none; appearance: none; opacity: 0 } .drawer-toggle:checked~.drawer-side { pointer-events: auto; visibility: visible; overflow-y: auto } .drawer-toggle:checked~.drawer-side>*:not(.drawer-overlay) { transform: translate(0) } .drawer-end { grid-auto-columns: auto max-content } .drawer-end .drawer-toggle~.drawer-content { grid-column-start: 1 } .drawer-end .drawer-toggle~.drawer-side { grid-column-start: 2; justify-items: end } .drawer-end .drawer-toggle~.drawer-side>*:not(.drawer-overlay) { transform: translate(100%) } [dir=rtl] .drawer-end .drawer-toggle~.drawer-side>*:not(.drawer-overlay) { transform: translate(-100%) } .drawer-end .drawer-toggle:checked~.drawer-side>*:not(.drawer-overlay) { transform: translate(0) } ================================================ FILE: components/modules/apps/app-side-bar/AppSideBar.tsx ================================================ import React from "react"; import { cookies } from "next/headers"; import { getApps } from "@/lib/db/apps"; import { createClient } from "@/lib/supabase/server"; import { AppSideBarList } from "./AppSideBarList"; export const AppSideBar = async () => { const cookieStore = cookies(); const supabase = await createClient(cookieStore); const apps = await getApps(supabase); return ( ); }; ================================================ FILE: components/modules/apps/app-side-bar/AppSideBarItem.tsx ================================================ import React from "react"; import Link from "next/link"; import { App } from "@/lib/db"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/Avatar"; type AppSideBarItemProps = Pick< App, "name" | "slug" | "description" | "logo_url" >; export const AppSideBarItem = ({ name, slug, description, logo_url: logoUrl, }: AppSideBarItemProps) => { return (
  • {logoUrl ? ( ) : null}

    {name}

    {description ? (

    {description}

    ) : null}
  • ); }; ================================================ FILE: components/modules/apps/app-side-bar/AppSideBarList.tsx ================================================ import { App } from "@/lib/db"; import { AppSideBarItem } from "./AppSideBarItem"; type AppSideBarListProps = { apps: App[] | null; }; export const AppSideBarList = ({ apps }: AppSideBarListProps) => { if (!apps?.length) { return
    No apps found
    ; } return (
      {apps.map((app) => { const { id, name, description, slug, logo_url } = app; return ( ); })}
    ); }; ================================================ FILE: components/modules/apps/app-side-bar/AppSidebarSection.tsx ================================================ import React from "react"; import { Heading5 } from "@/components/ui/typography"; type AppSidebarSectionProps = { title: string; children: React.ReactNode; }; export const AppSidebarSection = ({ title, children, }: AppSidebarSectionProps) => { return (
    {title} {children}
    ); }; ================================================ FILE: components/modules/apps/app-side-bar/index.ts ================================================ export * from "./AppSideBar"; ================================================ FILE: components/modules/apps/chat/ChatForm.tsx ================================================ import React from "react"; import { SendHorizonal } from "lucide-react"; import { MentionsInputProps, SuggestionDataItem } from "react-mentions"; import { Chat, ChatMemberProfile } from "@/lib/db"; import { useProfileStore } from "@/lib/stores/profile"; import { useEnterSubmit } from "@/hooks/useEnterSubmit"; import { Button } from "@/components/ui/Button"; import { ChatInput } from "@/components/ui/chat"; import { MobileDrawerControl } from "./MobileDrawerControls"; type ChatFormProps = { chatInput: string; chats: Chat[] | null; isChatStreamming: boolean; chatMembers: ChatMemberProfile[] | null; onSubmit: (e: React.FormEvent) => void; onInputChange: ( e: | React.ChangeEvent | React.ChangeEvent ) => void; }; export const ChatForm = ({ chats, isChatStreamming, chatMembers, chatInput, onSubmit, onInputChange, }: ChatFormProps) => { const { formRef, onKeyDown } = useEnterSubmit(); const currentProfile = useProfileStore((state) => state.profile); const mentionData: SuggestionDataItem[] = React.useMemo(() => { const mentionData = [{ id: "assistant", display: "Assistant" }]; if (!chatMembers) return mentionData; chatMembers.forEach((member) => { if (!member.profiles) return; mentionData.push({ id: member.profiles.id, display: member.profiles.username || "", }); }); return mentionData.filter((mention) => mention.id !== currentProfile?.id); }, [chatMembers, currentProfile?.id]); const handleOnChange: MentionsInputProps["onChange"] = (e) => { onInputChange({ target: { value: e.target.value }, } as React.ChangeEvent); }; return (
    ); }; ================================================ FILE: components/modules/apps/chat/ChatHistory.tsx ================================================ "use client"; import React from "react"; import { Chat } from "@/lib/db"; import { useChatIdFromPathName } from "@/hooks/useChatIdFromPathName"; import { Separator } from "@/components/ui/Separator"; import { Paragraph } from "@/components/ui/typography"; import { ChatHistoryItem } from "./ChatHistoryItem"; import { NewChatButton } from "./NewChatButton"; type ChatHistoryProps = { data: Chat[] | null; closeDrawer?: () => void; }; export const ChatHistory = ({ data, closeDrawer }: ChatHistoryProps) => { const chatId = useChatIdFromPathName(); return ( ); }; ================================================ FILE: components/modules/apps/chat/ChatHistoryDrawer.tsx ================================================ "use client"; import React from "react"; import { History } from "lucide-react"; import { Drawer } from "vaul"; import { Chat } from "@/lib/db"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/Button"; import { ChatHistory } from "./ChatHistory"; type ChatHistoryDrawerProps = { data: Chat[] | null; }; export const ChatHistoryDrawer = ({ data }: ChatHistoryDrawerProps) => { const [drawerOpen, setDrawerOpen] = React.useState(false); const onHistoryButtonClick = () => { setDrawerOpen(true); }; const closeDrawer = React.useCallback(() => { setDrawerOpen(false); }, []); return (
    ); }; ================================================ FILE: components/modules/apps/chat/ChatHistoryItem.tsx ================================================ import React from "react"; import Link from "next/link"; import { MessageCircle } from "lucide-react"; import { Chat } from "@/lib/db"; import { cn } from "@/lib/utils"; import { DeleteChatAction } from "./DeleteChatAction"; import { EditChatAction } from "./EditChatAction"; type ChatHistoryItemProps = { chat: Chat; isActive: boolean; closeDrawer?: () => void; }; export const ChatHistoryItem = ({ chat, isActive, closeDrawer, }: ChatHistoryItemProps) => { const renderActionButtons = () => { return (
    ); }; return (
  • {chat.name}

    {renderActionButtons()}
  • ); }; ================================================ FILE: components/modules/apps/chat/ChatLayout.tsx ================================================ import { MainLayout } from "@/components/ui/common/MainLayout"; interface ChatLayoutProps { children: React.ReactNode; leftSidebarElement: React.ReactNode; } export const ChatLayout = ({ children, leftSidebarElement, }: ChatLayoutProps) => { return (
    {leftSidebarElement}
    {children}
    ); }; ================================================ FILE: components/modules/apps/chat/ChatPanel.tsx ================================================ "use client"; import React from "react"; import { useRouter } from "next/navigation"; import { zodResolver } from "@hookform/resolvers/zod"; import { Message, useChat } from "ai/react"; import { useForm } from "react-hook-form"; import { v4 as uuidv4 } from "uuid"; import { containsChatBotTrigger } from "@/lib/chat-input"; import { Chat, ChatMemberProfile, Message as SupabaseMessage } from "@/lib/db"; import { useProfileStore } from "@/lib/stores/profile"; import { RealtimeChatMemberStatus, useSubscribeChatMessages, } from "@/hooks/useSubscribeChatMessages"; import { ChatList } from "@/components/ui/chat"; import { ChatScrollAnchor } from "@/components/ui/common/ChatScrollAnchor"; import { Separator } from "@/components/ui/Separator"; import { Sheet } from "@/components/ui/Sheet"; import { useToast } from "@/components/ui/use-toast"; import { revalidateChatLayout } from "./action"; import { ChatForm } from "./ChatForm"; import { ControlSidebarSheet } from "./control-side-bar/ControlSidebarSheet"; import { defaultSystemPrompt } from "./control-side-bar/data/models"; import { Header } from "./Header"; import { ChatParamSchema } from "./schema"; import { ChatParams } from "./types"; import { buildChatRequestParams } from "./utils"; const defaultValues: ChatParams = { description: defaultSystemPrompt, model: "gpt-3.5-turbo", temperature: [1], topP: [0.5], maxTokens: [250], frequencyPenalty: [0], presencePenalty: [0], }; export type ChatPanelProps = { chatId: Chat["id"]; initialMessages: Message[]; chats: Chat[] | null; chatParams?: ChatParams; isNewChat?: boolean; isChatHost?: boolean; chatMembers: ChatMemberProfile[] | null; defaultMemberSidebarLayout: number[]; }; export const ChatPanel = ({ chatId, chats, initialMessages, chatParams, isNewChat, isChatHost, chatMembers, defaultMemberSidebarLayout, }: ChatPanelProps) => { const { toast } = useToast(); const profile = useProfileStore((state) => state.profile); const scrollAreaRef = React.useRef(null); const [sidebarSheetOpen, setSidebarSheetOpen] = React.useState(false); const router = useRouter(); const [chatMemberWithStatus, setChatMemberWithStatus] = React.useState< ChatMemberProfile[] | null >(chatMembers); const { messages, input, setInput, handleInputChange, isLoading, stop, reload, error, setMessages, append, } = useChat({ id: chatId, api: "/api/chat", initialMessages, sendExtraMessageFields: true, onResponse: async (response) => { if (response?.headers.get("should-redirect-to-new-chat") === "true") { await revalidateChatLayout(); router.replace(`/apps/chat/${chatId}`); } }, onFinish: async () => { if (isNewChat) { await revalidateChatLayout(); router.replace(`/apps/chat/${chatId}`); } }, }); const handleChatMemberPresense = React.useCallback( (newState: RealtimeChatMemberStatus) => { if (!chatMembers?.length) { return; } const onlineMemberProfileIds = Object.values(newState).map( (value) => value[0].userId ); const updatedChatMembers: ChatMemberProfile[] = chatMembers.map( (member) => ({ ...member, status: onlineMemberProfileIds.includes(member.profiles?.id || "") ? "online" : "offline", }) ); setChatMemberWithStatus(updatedChatMembers); }, [chatMembers] ); const handleNewMessageInsert = React.useCallback( (newMessages: Message[]) => { setMessages(newMessages); }, [setMessages] ); useSubscribeChatMessages({ initialMessages: messages, chatId, currentUserId: profile?.id, newMessageInsertCallback: handleNewMessageInsert, chatMemberPresenceCallback: handleChatMemberPresense, }); const formReturn = useForm({ defaultValues: chatParams || defaultValues, mode: "onChange", resolver: zodResolver(ChatParamSchema), }); const chatRequestParams = React.useMemo(() => { const formValues = formReturn.getValues(); return buildChatRequestParams(formValues); }, [formReturn]); React.useEffect(() => { if (error) { toast({ title: "Error", description: "AI Assistant is not available at the moment. Please try again later.", variant: "destructive", }); } }, [error, toast]); React.useEffect(() => { if (!messages.length) { return; } scrollAreaRef.current?.scrollTo({ top: scrollAreaRef.current.scrollHeight, }); window.scrollTo({ top: document.body.scrollHeight }); }, [messages.length]); React.useEffect(() => { scrollAreaRef.current?.scrollTo({ top: scrollAreaRef.current.scrollHeight, }); window.scrollTo({ top: document.body.scrollHeight }); }, []); const handleOnChange = ( e: | React.ChangeEvent | React.ChangeEvent ) => { handleInputChange(e); }; const handleReloadMessages = React.useCallback( (id: SupabaseMessage["id"]) => { reload({ options: { body: { ...chatRequestParams, chatId, isRegenerate: true, regenerateMessageId: id, }, }, }); }, [chatId, chatRequestParams] ); const onSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!input || isLoading) { return; } append( { content: input, role: "user", id: uuidv4(), data: { profile_id: profile?.id || "", chat_id: chatId, }, }, { options: { body: { ...chatRequestParams, chatId, isNewChat, enableChatAssistant: containsChatBotTrigger(input), }, }, } ); setInput(""); }; const closeSidebarSheet = React.useCallback(() => { setSidebarSheetOpen(false); }, []); return (
    ); }; ================================================ FILE: components/modules/apps/chat/CodeBlock.tsx ================================================ // Inspired by Chatbot-UI and modified to fit the needs of this project // @see https://github.com/mckaywrigley/chatbot-ui/blob/main/components/Markdown/CodeBlock.tsx "use client"; import React, { FC, memo } from "react"; import { Check, Copy, Download } from "lucide-react"; import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; import { oneDark, oneLight, } from "react-syntax-highlighter/dist/cjs/styles/prism"; import { useActiveThemeColor } from "@/hooks/useActiveTheme"; import { useCopyToClipboard } from "@/hooks/useCopyToClipboard"; import { Button } from "@/components/ui/Button"; interface Props { language: string; value: string; } interface languageMap { [key: string]: string | undefined; } export const programmingLanguages: languageMap = { javascript: ".js", python: ".py", java: ".java", c: ".c", cpp: ".cpp", "c++": ".cpp", "c#": ".cs", ruby: ".rb", php: ".php", swift: ".swift", "objective-c": ".m", kotlin: ".kt", typescript: ".ts", go: ".go", perl: ".pl", rust: ".rs", scala: ".scala", haskell: ".hs", lua: ".lua", shell: ".sh", sql: ".sql", html: ".html", css: ".css", // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component }; export const generateRandomString = (length: number, lowercase = false) => { const chars = "ABCDEFGHJKLMNPQRSTUVWXY3456789"; // excluding similar looking characters like Z, 2, I, 1, O, 0 let result = ""; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } return lowercase ? result.toLowerCase() : result; }; const CodeBlock: FC = memo(({ language, value }) => { const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 }); const [codeBlockStyle, setCodeBlockStyle] = React.useState(oneLight); const theme = useActiveThemeColor(); React.useEffect(() => { setCodeBlockStyle(theme === "dark" ? oneDark : oneLight); }, [theme]); const downloadAsFile = () => { if (typeof window === "undefined") { return; } const fileExtension = programmingLanguages[language] || ".file"; const suggestedFileName = `file-${generateRandomString( 3, true )}${fileExtension}`; const fileName = window.prompt("Enter file name" || "", suggestedFileName); if (!fileName) { // User pressed cancel on prompt. return; } const blob = new Blob([value], { type: "text/plain" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.download = fileName; link.href = url; link.style.display = "none"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; const onCopy = () => { if (isCopied) return; copyToClipboard(value); }; return (
    {language}
    {value}
    ); }); CodeBlock.displayName = "CodeBlock"; export { CodeBlock }; ================================================ FILE: components/modules/apps/chat/DeleteChatAction.tsx ================================================ import React from "react"; import { useRouter } from "next/navigation"; import { Loader, Trash2 } from "lucide-react"; import { cn } from "@/lib/utils"; import { useChatIdFromPathName } from "@/hooks/useChatIdFromPathName"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/AlertDialog"; import { Button, buttonVariants } from "@/components/ui/Button"; import { toast } from "@/components/ui/use-toast"; import { deleteChat } from "./action"; import { ChatActionProps } from "./types"; export const DeleteChatAction = ({ chat, ...rest }: ChatActionProps) => { const [isAlertOpen, setIsAlertOpen] = React.useState(false); const [pendingDeleteChat, startDeleteChat] = React.useTransition(); const { replace } = useRouter(); const chatIdFromPathName = useChatIdFromPathName(); const onDelete = (e: React.MouseEvent) => { e.preventDefault(); startDeleteChat(async () => { try { await deleteChat(chat.id); toast({ title: "Success", description: "Your chat has been deleted.", }); if (chatIdFromPathName === chat.id) { replace("/apps/chat"); } setIsAlertOpen(false); } catch (error) { toast({ title: "Error", description: "Failed to delete chat. Please try again.", variant: "destructive", }); } }); }; return ( Are you sure you want to delete this chat? This action cannot be undone. This will permanently delete your chat. Cancel {pendingDeleteChat ? ( ) : ( "Delete" )} ); }; ================================================ FILE: components/modules/apps/chat/EditChatAction.tsx ================================================ import React from "react"; import { Edit, Loader } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/AlertDialog"; import { Button } from "@/components/ui/Button"; import { Input } from "@/components/ui/Input"; import { toast } from "@/components/ui/use-toast"; import { updateChat } from "./action"; import { ChatActionProps } from "./types"; export const EditChatAction = ({ chat, ...rest }: ChatActionProps) => { const [isAlertOpen, setIsAlertOpen] = React.useState(false); const [pendingUpdateChat, startUpdateChat] = React.useTransition(); const [inputValue, setInputValue] = React.useState(chat.name || ""); const handleDelete = () => { startUpdateChat(async () => { try { await updateChat({ id: chat.id, name: inputValue, }); toast({ title: "Success", description: "Your chat has been updated.", }); setIsAlertOpen(false); } catch (error) { toast({ title: "Error", description: "Failed to update chat. Please try again.", variant: "destructive", }); } }); }; const onChange = (e: React.ChangeEvent) => { setInputValue(e.target.value); }; const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); handleDelete(); } }; const onEdit = (e: React.MouseEvent) => { e.stopPropagation(); }; const onDelete = (e: React.MouseEvent) => { e.preventDefault(); handleDelete(); }; return ( Edit your chat title
    Cancel {pendingUpdateChat ? ( ) : ( "Update" )}
    ); }; ================================================ FILE: components/modules/apps/chat/Header.tsx ================================================ import React from "react"; import { Heading2 } from "@/components/ui/typography"; export const Header = () => { return (
    GPT AI Assistant
    ); }; ================================================ FILE: components/modules/apps/chat/MobileDrawerControls.tsx ================================================ import React from "react"; import { PanelRight } from "lucide-react"; import { Chat } from "@/lib/db"; import { Button } from "@/components/ui/Button"; import { SheetTrigger } from "@/components/ui/Sheet"; import { ChatHistoryDrawer } from "./ChatHistoryDrawer"; type MobileDrawerControlProps = { chats: Chat[] | null; }; export const MobileDrawerControl = React.memo(function MobileDrawerControl({ chats, }: MobileDrawerControlProps) { return ( <>
    ); }); ================================================ FILE: components/modules/apps/chat/NewChatButton.tsx ================================================ "use client"; import React from "react"; import Link from "next/link"; import { Plus } from "lucide-react"; import { cn } from "@/lib/utils"; import { buttonVariants } from "@/components/ui/Button"; type NewChatButtonProps = { closeDrawer?: () => void; }; export const NewChatButton = ({ closeDrawer }: NewChatButtonProps) => { return ( ); }; ================================================ FILE: components/modules/apps/chat/SystemPromptControl.tsx ================================================ import React from "react"; import { Message, UseChatHelpers } from "ai/react"; import { useFormContext } from "react-hook-form"; import { Button } from "@/components/ui/Button"; import { Label } from "@/components/ui/Label"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/Popover"; import { TextArea } from "@/components/ui/TextArea"; import { Subtle } from "@/components/ui/typography"; import { ChatParams } from "./types"; type SystemPromptControlProps = Pick< UseChatHelpers, "setMessages" | "messages" >; export const SystemPromptControl = ({ setMessages, messages, }: SystemPromptControlProps) => { const [isPopoverOpen, setIsPopoverOpen] = React.useState(false); const { getValues, setValue } = useFormContext(); const formValues = getValues(); const { description } = formValues; const [systemPromptInputValue, setSystemPromptInputValue] = React.useState< string | undefined >(description); const handlePopoverOpenChange = (isOpen: boolean) => { if (isOpen) { if (description !== systemPromptInputValue) { setSystemPromptInputValue(description); } } setIsPopoverOpen(isOpen); }; const handleSystemPromptInputChange = ( e: React.ChangeEvent ) => { setSystemPromptInputValue(e.target.value); }; const handleSave = () => { if (!systemPromptInputValue) { return; } const systemMessage: Message = { role: "system", content: systemPromptInputValue, id: "system-prompt", }; setMessages([systemMessage, ...messages]); setValue("description", systemPromptInputValue); setIsPopoverOpen(false); }; return (
    {description}

    Set system prompt

    {`Set a custom system prompt to be prepended to the user's input. This is useful for giving the AI some context about the conversation.`}