Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to dynamic io #557

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions app/(chat)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { cookies } from 'next/headers';

import { AppSidebar } from '@/components/app-sidebar';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import {
SidebarGroup,
SidebarGroupContent,
SidebarInset,
SidebarProvider,
} from '@/components/ui/sidebar';

import { auth } from '../(auth)/auth';
import { Suspense } from 'react';
import { notFound } from 'next/navigation';
import { SidebarDataWrapper } from './sidebar-data-wrapper';

export const experimental_ppr = true;

Expand All @@ -14,11 +22,45 @@ export default async function Layout({
}) {
const [session, cookieStore] = await Promise.all([auth(), cookies()]);
const isCollapsed = cookieStore.get('sidebar:state')?.value !== 'true';
if (!session?.user) {
return notFound();
}

return (
<SidebarProvider defaultOpen={!isCollapsed}>
<AppSidebar user={session?.user} />
<AppSidebar user={session?.user}>
<Suspense fallback={<SidebarLoading />}>
<SidebarDataWrapper user={session?.user} />
</Suspense>
</AppSidebar>
<SidebarInset>{children}</SidebarInset>
</SidebarProvider>
);
}

function SidebarLoading() {
return (
<SidebarGroup>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50">Today</div>
<SidebarGroupContent>
<div className="flex flex-col">
{[44, 32, 28, 64, 52].map((item) => (
<div
key={item}
className="rounded-md h-8 flex gap-2 px-2 items-center"
>
<div
className="h-4 rounded-md flex-1 max-w-[--skeleton-width] bg-sidebar-accent-foreground/10"
style={
{
'--skeleton-width': `${item}%`,
} as React.CSSProperties
}
/>
</div>
))}
</div>
</SidebarGroupContent>
</SidebarGroup>
);
}
2 changes: 2 additions & 0 deletions app/(chat)/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { cookies } from 'next/headers';
import { connection } from 'next/server';

import { Chat } from '@/components/chat';
import { DEFAULT_MODEL_NAME, models } from '@/lib/ai/models';
import { generateUUID } from '@/lib/utils';

export default async function Page() {
await connection();
const id = generateUUID();

const cookieStore = await cookies();
Expand Down
17 changes: 17 additions & 0 deletions app/(chat)/sidebar-data-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { User } from 'next-auth';
import { getChatsByUserId } from '@/lib/db/queries';
import { unstable_cacheTag as cacheTag } from 'next/cache';
import { SidebarHistory } from '@/components/sidebar-history';

export async function getChats(id: string) {
'use cache';
cacheTag('history');
const chats = await getChatsByUserId({ id });
return chats;
}

export async function SidebarDataWrapper({ user }: { user: User }) {
// biome-ignore lint: Forbidden non-null assertion.
const chats = await getChats(user?.id!);
return <SidebarHistory user={user} history={chats} />;
}
10 changes: 5 additions & 5 deletions components/app-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type { User } from 'next-auth';
import { useRouter } from 'next/navigation';

import { PlusIcon } from '@/components/icons';
import { SidebarHistory } from '@/components/sidebar-history';
import { SidebarUserNav } from '@/components/sidebar-user-nav';
import { Button } from '@/components/ui/button';
import {
Expand All @@ -20,7 +19,10 @@ import {
import { BetterTooltip } from '@/components/ui/tooltip';
import Link from 'next/link';

export function AppSidebar({ user }: { user: User | undefined }) {
export function AppSidebar({
user,
children,
}: { user: User | undefined; children: React.ReactNode }) {
const router = useRouter();
const { setOpenMobile } = useSidebar();

Expand Down Expand Up @@ -58,9 +60,7 @@ export function AppSidebar({ user }: { user: User | undefined }) {
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<SidebarGroup className="-mx-2">
<SidebarHistory user={user} />
</SidebarGroup>
<SidebarGroup className="-mx-2">{children}</SidebarGroup>
</SidebarContent>
<SidebarFooter className="gap-0 -mx-2">
{user && (
Expand Down
4 changes: 3 additions & 1 deletion components/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Block, type UIBlock } from './block';
import { BlockStreamHandler } from './block-stream-handler';
import { MultimodalInput } from './multimodal-input';
import { Overview } from './overview';
import { revalidateTag } from 'next/cache';

export function Chat({
id,
Expand All @@ -43,7 +44,8 @@ export function Chat({
body: { id, modelId: selectedModelId },
initialMessages,
onFinish: () => {
mutate('/api/history');
revalidateTag('history');
// mutate('/api/history');
},
});

Expand Down
3 changes: 2 additions & 1 deletion components/multimodal-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { ArrowUpIcon, PaperclipIcon, StopIcon } from './icons';
import { PreviewAttachment } from './preview-attachment';
import { Button } from './ui/button';
import { Textarea } from './ui/textarea';
import { revalidateTag } from 'next/cache';

const suggestedActions = [
{
Expand Down Expand Up @@ -130,7 +131,7 @@ export function MultimodalInput({

setAttachments([]);
setLocalStorageInput('');

revalidateTag('history');
if (width && width > 768) {
textareaRef.current?.focus();
}
Expand Down
65 changes: 15 additions & 50 deletions components/sidebar-history.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import { isToday, isYesterday, subMonths, subWeeks } from 'date-fns';
import Link from 'next/link';
import { useParams, usePathname, useRouter } from 'next/navigation';
import type { User } from 'next-auth';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import useSWR from 'swr';
import { useState } from 'react';

import { MoreHorizontalIcon, TrashIcon } from '@/components/icons';
import {
Expand Down Expand Up @@ -35,7 +33,7 @@ import {
useSidebar,
} from '@/components/ui/sidebar';
import type { Chat } from '@/lib/db/schema';
import { fetcher } from '@/lib/utils';
import { revalidateTag } from 'next/cache';

type GroupedChats = {
today: Chat[];
Expand Down Expand Up @@ -85,21 +83,21 @@ const ChatItem = ({
</SidebarMenuItem>
);

export function SidebarHistory({ user }: { user: User | undefined }) {
export function SidebarHistory({
user,
history,
}: {
user: User | undefined;
history: {
id: string;
createdAt: Date;
title: string;
userId: string;
}[];
}) {
const { setOpenMobile } = useSidebar();
const { id } = useParams();
const pathname = usePathname();
const {
data: history,
isLoading,
mutate,
} = useSWR<Array<Chat>>(user ? '/api/history' : null, fetcher, {
fallbackData: [],
});

useEffect(() => {
mutate();
}, [pathname, mutate]);

const [deleteId, setDeleteId] = useState<string | null>(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
Expand All @@ -112,11 +110,7 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
toast.promise(deletePromise, {
loading: 'Deleting chat...',
success: () => {
mutate((history) => {
if (history) {
return history.filter((h) => h.id !== id);
}
});
revalidateTag('history');
return 'Chat deleted successfully';
},
error: 'Failed to delete chat',
Expand All @@ -141,35 +135,6 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
);
}

if (isLoading) {
return (
<SidebarGroup>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Today
</div>
<SidebarGroupContent>
<div className="flex flex-col">
{[44, 32, 28, 64, 52].map((item) => (
<div
key={item}
className="rounded-md h-8 flex gap-2 px-2 items-center"
>
<div
className="h-4 rounded-md flex-1 max-w-[--skeleton-width] bg-sidebar-accent-foreground/10"
style={
{
'--skeleton-width': `${item}%`,
} as React.CSSProperties
}
/>
</div>
))}
</div>
</SidebarGroupContent>
</SidebarGroup>
);
}

if (history?.length === 0) {
return (
<SidebarGroup>
Expand Down
1 change: 1 addition & 0 deletions next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const nextConfig: NextConfig = {
/* config options here */
experimental: {
ppr: true,
dynamicIO: true,
},
images: {
remotePatterns: [
Expand Down