An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Fix async issue in Header component and pass chats to History component
Yoshiki Miuraa554fd5e5b8d
diff --git a/app/action.tsx b/app/action.tsxindex 1c2571c3..1b334461 100644--- a/app/action.tsx+++ b/app/action.tsx@@ -36,8 +36,6 @@ async function submit(formData?: FormData, skip?: boolean) {// goupeiId is used to group the messages for collapseconst groupeId = nanoid()- console.log('submit', aiState.get())-const useSpecificAPI = process.env.USE_SPECIFIC_API_FOR_WRITER === 'true'const maxMessages = useSpecificAPI ? 5 : 10// Limit the number of messages to the maximum@@ -60,8 +58,6 @@ async function submit(formData?: FormData, skip?: boolean) {? 'input_related': 'inquiry'- console.log('content', content)-// Add the user message to the stateif (content) {aiState.update({@@ -172,26 +168,30 @@ async function submit(formData?: FormData, skip?: boolean) {streamText.done()}- aiState.update({- ...aiState.get(),- messages: [- ...aiState.get().messages,- {- id: groupeId,- role: 'assistant',- content: answer,- type: 'answer'- }- ]- })-if (!errorOccurred) {// Generate related queriesconst relatedQueries = await querySuggestor(uiStream, messages)- aiState.update({+ // Add follow-up panel+ uiStream.append(+ <Section title="Follow-up">+ <FollowupPanel />+ </Section>+ )++ // Add the answer, related queries, and follow-up panel to the state+ // Wait for 1 second before adding the answer to the state+ await new Promise(resolve => setTimeout(resolve, 1000))++ aiState.done({...aiState.get(),messages: [...aiState.get().messages,+ {+ id: groupeId,+ role: 'assistant',+ content: answer,+ type: 'answer'+ },{id: groupeId,role: 'assistant',@@ -206,20 +206,10 @@ async function submit(formData?: FormData, skip?: boolean) {}]})-- // Add follow-up panel- uiStream.append(- <Section title="Follow-up">- <FollowupPanel />- </Section>- )}isGenerating.done(false)uiStream.done()- aiState.done(aiState.get())-- console.log('aiState', aiState.get().chatId)}processEvents()diff --git a/bun.lockb b/bun.lockbindex 63e4d371..1df8ab2f 100755Binary files a/bun.lockb and b/bun.lockb differdiff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 18a6526e..0e9d0a4a 100644--- a/components/chat-messages.tsx+++ b/components/chat-messages.tsx@@ -40,16 +40,19 @@ export function ChatMessages({ messages }: ChatMessagesProps) {return (<>{groupedMessagesArray.map(- (groupedMessage: {- id: string- components: React.ReactNode[]- isCollapsed?: StreamableValue<boolean>- }) => (+ (+ groupedMessage: {+ id: string+ components: React.ReactNode[]+ isCollapsed?: StreamableValue<boolean>+ },+ index+ ) => (<CollapsibleMessage- key={groupedMessage.id}+ key={`${groupedMessage.id}`}message={{id: groupedMessage.id,- component: <>{groupedMessage.components}</>,+ component: <div key={index}>{groupedMessage.components}</div>,isCollapsed: groupedMessage.isCollapsed}}isLastMessage={diff --git a/components/chat.tsx b/components/chat.tsxindex 5c56f2b4..22be44de 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -24,9 +24,12 @@ export function Chat({ id }: ChatProps) {useEffect(() => {if (aiState.messages[aiState.messages.length - 1]?.type === 'followup') {- router.refresh()+ // Refresh the page after 1 second to chat history updates+ setTimeout(() => {+ router.refresh()+ }, 1000)}- }, [aiState, messages, router])+ }, [aiState, router])return (<div className="px-8 sm:px-12 pt-6 md:pt-8 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4">diff --git a/components/header.tsx b/components/header.tsxindex 144665ad..39caff9e 100644--- a/components/header.tsx+++ b/components/header.tsx@@ -1,12 +1,10 @@-'use client'-import React from 'react'import { ModeToggle } from './mode-toggle'import { IconLogo } from './ui/icons'import { cn } from '@/lib/utils'-import { History } from './history'+import HistoryContainer from './history-container'-export const Header: React.FC = () => {+export const Header: React.FC = async () => {return (<header className="fixed w-full p-1 md:p-2 flex justify-between items-center z-10 backdrop-blur md:backdrop-blur-none bg-background/80 md:bg-transparent"><div>@@ -17,9 +15,7 @@ export const Header: React.FC = () => {</div><div className="flex gap-0.5"><ModeToggle />- <div className="sm:hidden block">- <History location="header" />- </div>+ <HistoryContainer location="header" /></div></header>)diff --git a/components/history-container.tsx b/components/history-container.tsxnew file mode 100644index 00000000..1789fb99--- /dev/null+++ b/components/history-container.tsx@@ -0,0 +1,24 @@+import React from 'react'+import { History } from './history'+import { getChats } from '@/lib/actions/chat'+import { cache } from 'react'++type HistoryContainerProps = {+ location: 'sidebar' | 'header'+}+const loadChats = cache(async (userId?: string) => {+ return await getChats(userId)+})++const HistoryContainer: React.FC<HistoryContainerProps> = async ({+ location+}) => {+ const chats = await loadChats('anonymous')+ return (+ <div className="sm:hidden block">+ <History location={location} chats={chats} />+ </div>+ )+}++export default HistoryContainerdiff --git a/components/history-item.tsx b/components/history-item.tsxindex 0d8f3ee6..ea7a3b29 100644--- a/components/history-item.tsx+++ b/components/history-item.tsx@@ -16,7 +16,7 @@ const formatDateWithTime = (date: Date | string) => {const yesterday = new Date()yesterday.setDate(yesterday.getDate() - 1)- const formatTime = date => {+ const formatTime = (date: Date) => {return date.toLocaleString('en-US', {hour: '2-digit',minute: '2-digit',diff --git a/components/search-related.tsx b/components/search-related.tsxindex c7d8e318..b61e4029 100644--- a/components/search-related.tsx+++ b/components/search-related.tsx@@ -1,9 +1,14 @@'use client'-import React from 'react'+import React, { useEffect, useState } from 'react'import { Button } from './ui/button'import { ArrowRight } from 'lucide-react'-import { useActions, useStreamableValue, useUIState } from 'ai/rsc'+import {+ useActions,+ useStreamableValue,+ useUIState,+ readStreamableValue+} from 'ai/rsc'import { AI } from '@/app/action'import { UserMessage } from './user-message'import { PartialRelated } from '@/lib/schema/related'diff --git a/lib/agents/query-suggestor.tsx b/lib/agents/query-suggestor.tsxindex f55d73ae..05ecd1e1 100644--- a/lib/agents/query-suggestor.tsx+++ b/lib/agents/query-suggestor.tsx@@ -4,7 +4,6 @@ import { PartialRelated, relatedSchema } from '@/lib/schema/related'import { Section } from '@/components/section'import SearchRelated from '@/components/search-related'import { OpenAI } from '@ai-sdk/openai'-import { PartialInquiry } from '../schema/inquiry'export async function querySuggestor(uiStream: ReturnType<typeof createStreamableUI>,@@ -44,11 +43,14 @@ export async function querySuggestor(}).then(async result => {for await (const obj of result.partialObjectStream) {- objectStream.update(obj)- finalRelatedQueries = obj+ if (obj.items) {+ objectStream.update(obj)+ finalRelatedQueries = obj+ }}}).finally(() => {+ console.log('done', finalRelatedQueries)objectStream.done()})diff --git a/package.json b/package.jsonindex 8f9632f3..8b199bdb 100644--- a/package.json+++ b/package.json@@ -25,7 +25,7 @@"@radix-ui/react-tooltip": "^1.0.7","@tailwindcss/typography": "^0.5.12","@upstash/redis": "^1.30.0",- "ai": "3.0.16",+ "ai": "3.0.21","class-variance-authority": "^0.7.0","clsx": "^2.1.0","embla-carousel-react": "^8.0.0",