An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor: Fix build error
Yoshiki Miura643334103a97
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsxindex a8177c57..9e7eaef8 100644--- a/app/search/[id]/page.tsx+++ b/app/search/[id]/page.tsx@@ -4,22 +4,22 @@ import { getChat } from '@/lib/actions/chat'export const maxDuration = 60-export interface SearchPageProps {- params: {- id: string- }-}--export async function generateMetadata({ params }: SearchPageProps) {- const chat = await getChat(params.id, 'anonymous')+export async function generateMetadata(props: {+ params: Promise<{ id: string }>+}) {+ const { id } = await props.params+ const chat = await getChat(id, 'anonymous')return {title: chat?.title.toString().slice(0, 50) || 'Search'}}-export default async function SearchPage({ params }: SearchPageProps) {+export default async function SearchPage(props: {+ params: Promise<{ id: string }>+}) {const userId = 'anonymous'- const chat = await getChat(params.id, userId)+ const { id } = await props.params+ const chat = await getChat(id, userId)if (!chat) {redirect('/')diff --git a/app/search/page.tsx b/app/search/page.tsxindex 6b4e6a05..8b7ade7b 100644--- a/app/search/page.tsx+++ b/app/search/page.tsx@@ -3,12 +3,11 @@ import { redirect } from 'next/navigation'export const maxDuration = 60-export default function Page({- searchParams-}: {- searchParams: { q: string }+export default async function SearchPage(props: {+ searchParams: Promise<{ q: string }>}) {- if (!searchParams.q) {+ const { q } = await props.searchParams+ if (!q) {redirect('/')}diff --git a/app/share/[id]/page.tsx b/app/share/[id]/page.tsxindex c2b0d893..482c9bc9 100644--- a/app/share/[id]/page.tsx+++ b/app/share/[id]/page.tsx@@ -1,16 +1,12 @@import { notFound } from 'next/navigation'import { Chat } from '@/components/chat'import { getSharedChat } from '@/lib/actions/chat'-import { AI } from '@/app/actions'-export interface SharePageProps {- params: {- id: string- }-}--export async function generateMetadata({ params }: SharePageProps) {- const chat = await getSharedChat(params.id)+export async function generateMetadata(props: {+ params: Promise<{ id: string }>+}) {+ const { id } = await props.params+ const chat = await getSharedChat(id)if (!chat || !chat.sharePath) {return notFound()@@ -21,22 +17,15 @@ export async function generateMetadata({ params }: SharePageProps) {}}-export default async function SharePage({ params }: SharePageProps) {- const chat = await getSharedChat(params.id)+export default async function SharePage(props: {+ params: Promise<{ id: string }>+}) {+ const { id } = await props.params+ const chat = await getSharedChat(id)if (!chat || !chat.sharePath) {notFound()}- return (- <AI- initialAIState={{- chatId: chat.id,- messages: chat.messages,- isSharePage: true- }}- >- <Chat id={params.id} />- </AI>- )+ return <Chat />}diff --git a/bun.lockb b/bun.lockbindex 197038c2..2cd6f3c5 100755Binary files a/bun.lockb and b/bun.lockb differdiff --git a/components/copilot-display.tsx b/components/copilot-display.tsxdeleted file mode 100644index 3ab2f57e..00000000--- a/components/copilot-display.tsx+++ /dev/null@@ -1,33 +0,0 @@-'use client'--import React from 'react'-import { Check } from 'lucide-react'-import { Card } from './ui/card'-import { IconLogo } from './ui/icons'--interface CopilotDisplayProps {- content: string-}--export function CopilotDisplay({ content }: CopilotDisplayProps) {- try {- const json = JSON.parse(content)- const formDataEntries = Object.entries(json)- const query = formDataEntries- .filter(- ([key, value]) =>- value === 'on' || (key === 'additional_query' && value !== '')- )- .map(([key, value]) => (key === 'additional_query' ? value : key))- .join(', ')-- return (- <Card className="p-3 md:p-4 w-full flex justify-between items-center">- <h5 className="text-muted-foreground text-xs truncate">{query}</h5>- <Check size={16} className="text-green-500 w-4 h-4" />- </Card>- )- } catch (error) {- return null- }-}diff --git a/components/copilot.tsx b/components/copilot.tsxdeleted file mode 100644index 04529fc7..00000000--- a/components/copilot.tsx+++ /dev/null@@ -1,214 +0,0 @@-'use client'--import React, { useEffect, useState } from 'react'-import { PartialInquiry } from '@/lib/schema/inquiry'-import { Input } from './ui/input'-import { Checkbox } from './ui/checkbox'-import { Button } from './ui/button'-import { Card } from './ui/card'-import { ArrowRight, Check, FastForward, Sparkles } from 'lucide-react'-import {- StreamableValue,- useActions,- useStreamableValue,- useUIState-} from 'ai/rsc'-import type { AI } from '@/app/actions'-import { useAppState } from '@/lib/utils/app-state'-import { useLocalStorage } from '@/lib/hooks/use-local-storage'-import { models } from '@/lib/types/models'-import { getDefaultModelId } from '@/lib/utils'--export type CopilotProps = {- inquiry?: StreamableValue<PartialInquiry>-}--export const Copilot: React.FC<CopilotProps> = ({ inquiry }: CopilotProps) => {- const [completed, setCompleted] = useState(false)- const [query, setQuery] = useState('')- const [skipped, setSkipped] = useState(false)- const [data, error, pending] = useStreamableValue<PartialInquiry>(inquiry)- const [checkedOptions, setCheckedOptions] = useState<{- [key: string]: boolean- }>({})- const [isButtonDisabled, setIsButtonDisabled] = useState(true)- const [, setMessages] = useUIState<typeof AI>()- const { submit } = useActions()- const { isGenerating, setIsGenerating } = useAppState()- const [object, setObject] = useState<PartialInquiry>()- const [selectedModelId] = useLocalStorage<string>(- 'selectedModel',- getDefaultModelId(models)- )-- const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- setQuery(event.target.value)- checkIfButtonShouldBeEnabled()- }-- const handleOptionChange = (selectedOption: string) => {- const updatedCheckedOptions = {- ...checkedOptions,- [selectedOption]: !checkedOptions[selectedOption]- }- setCheckedOptions(updatedCheckedOptions)- checkIfButtonShouldBeEnabled(updatedCheckedOptions)- }-- const checkIfButtonShouldBeEnabled = (currentOptions = checkedOptions) => {- const anyCheckboxChecked = Object.values(currentOptions).some(- checked => checked- )- setIsButtonDisabled(!(anyCheckboxChecked || query))- }-- const updatedQuery = () => {- const selectedOptions = Object.entries(checkedOptions)- .filter(([, checked]) => checked)- .map(([option]) => option)- return [...selectedOptions, query].filter(Boolean).join(', ')- }-- useEffect(() => {- checkIfButtonShouldBeEnabled()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [query])-- useEffect(() => {- if (!data) return- setObject(data)- }, [data])-- const onFormSubmit = async (- e: React.FormEvent<HTMLFormElement>,- skip?: boolean- ) => {- e.preventDefault()-- if (isGenerating) return-- setIsGenerating(true)- setCompleted(true)- setSkipped(skip || false)-- // Always create FormData- const formData = new FormData()-- // Add model information- formData.set('model', selectedModelId)-- // If not skipping, add form data from the event- if (!skip) {- const form = e.target as HTMLFormElement- const formEntries = Array.from(new FormData(form).entries())- formEntries.forEach(([key, value]) => {- if (key !== 'model') {- // Don't override model- formData.append(key, value)- }- })- }-- const response = await submit(formData, skip)- setMessages(currentMessages => [...currentMessages, response])- }-- const handleSkip = (e: React.MouseEvent<HTMLButtonElement>) => {- onFormSubmit(e as unknown as React.FormEvent<HTMLFormElement>, true)- }-- if (error) {- return (- <Card className="p-4 w-full flex justify-between items-center">- <div className="flex items-center space-x-2">- <Sparkles className="w-4 h-4" />- <h5 className="text-muted-foreground text-xs truncate">- {`error: ${error}`}- </h5>- </div>- </Card>- )- }-- if (skipped) {- return null- }-- if (completed) {- return (- <Card className="p-3 md:p-4 w-full flex justify-between items-center">- <div className="flex items-center space-x-2 flex-1 min-w-0">- <h5 className="text-muted-foreground text-xs truncate">- {updatedQuery()}- </h5>- </div>- <Check size={16} className="text-green-500 w-4 h-4" />- </Card>- )- } else {- return (- <Card className="p-4 rounded-lg w-full mx-auto">- <div className="mb-4">- <p className="text-lg text-foreground text-semibold ml-2">- {object?.question}- </p>- </div>- <form onSubmit={onFormSubmit}>- <div className="flex flex-wrap justify-start mb-4">- {object?.options?.map((option, index) => (- <div- key={`option-${index}`}- className="flex items-center space-x-1.5 mb-2"- >- <Checkbox- id={option?.value}- name={option?.value}- onCheckedChange={() =>- handleOptionChange(option?.label as string)- }- />- <label- className="text-sm whitespace-nowrap pr-4"- htmlFor={option?.value}- >- {option?.label}- </label>- </div>- ))}- </div>- {object?.allowsInput && (- <div className="mb-6 flex flex-col space-y-2 text-sm">- <label className="text-muted-foreground" htmlFor="query">- {object?.inputLabel}- </label>- <Input- type="text"- name="additional_query"- className="w-full"- id="query"- placeholder={object?.inputPlaceholder}- value={query}- onChange={handleInputChange}- />- </div>- )}- <div className="flex justify-end space-x-2">- <Button- type="button"- variant="outline"- onClick={handleSkip}- disabled={pending || isGenerating}- >- <FastForward size={16} className="mr-1" />- Skip- </Button>- <Button type="submit" disabled={isButtonDisabled || pending}>- <ArrowRight size={16} className="mr-1" />- Send- </Button>- </div>- </form>- </Card>- )- }-}diff --git a/components/error-card.tsx b/components/error-card.tsxdeleted file mode 100644index 6ea40dd9..00000000--- a/components/error-card.tsx+++ /dev/null@@ -1,58 +0,0 @@-'use client'--import React from 'react'-import { Card } from './ui/card'-import { Button } from './ui/button'-import { RefreshCcw } from 'lucide-react'-import { Label } from './ui/label'-import { useUIState, useActions, useAIState } from 'ai/rsc'-import { AI } from '@/app/actions'-import { AIMessage } from '@/lib/types'--type ErrorCardProps = {- errorMessage: string-}--export const ErrorCard: React.FC<ErrorCardProps> = ({ errorMessage }) => {- const [messages, setMessages] = useUIState<typeof AI>()- const [aiState, setAIState] = useAIState<typeof AI>()- const { submit } = useActions()-- const handleRetry = async () => {- // Remove the last message from the UIState- setMessages(messages.slice(0, -1))-- const aiMessages = aiState.messages- // Get the last message with role = user- const lastUserMessage = [...aiMessages]- .reverse()- .find(m => m.role === 'user')-- let retryMessages: AIMessage[] = []- // Remove messages after lastUserMessage, cannot identify by id, so process by order- if (lastUserMessage) {- const lastUserMessageIndex = aiMessages.findIndex(- m => m === lastUserMessage- )- retryMessages = aiMessages.slice(0, lastUserMessageIndex + 1)- }- // Request retry from the server and add the response to the current messages- const response = await submit(undefined, false, retryMessages)- setMessages(currentMessages => [...currentMessages, response])- }-- return (- <Card className="p-4">- <form- className="flex flex-col items-center space-y-4"- action={handleRetry}- >- <Label>{errorMessage}</Label>- <Button size="sm" className="w-fit" type="submit">- <RefreshCcw size={14} className="mr-1" />- Retry- </Button>- </form>- </Card>- )-}diff --git a/components/history.tsx b/components/history.tsxindex 63206e79..3760a5fc 100644--- a/components/history.tsx+++ b/components/history.tsx@@ -15,7 +15,6 @@ import { cn } from '@/lib/utils'import { History as HistoryIcon } from 'lucide-react'import { Suspense } from 'react'import { HistorySkeleton } from './history-skeleton'-import { useAppState } from '@/lib/utils/app-state'type HistoryProps = {location: 'sidebar' | 'header'@@ -25,7 +24,6 @@ type HistoryProps = {export function History({ location, children }: HistoryProps) {const router = useRouter()const [isPending, startTransition] = useTransition()- const { isGenerating, setIsGenerating } = useAppState()const onOpenChange = (open: boolean) => {if (open) {@@ -44,7 +42,6 @@ export function History({ location, children }: HistoryProps) {className={cn({'rounded-full text-foreground/30': location === 'sidebar'})}- disabled={isGenerating}>{location === 'header' ? <Menu /> : <ChevronLeft size={16} />}</Button>diff --git a/components/ui/codeblock.tsx b/components/ui/codeblock.tsxindex 476f3197..ac353da6 100644--- a/components/ui/codeblock.tsx+++ b/components/ui/codeblock.tsx@@ -57,7 +57,7 @@ const CodeBlock: FC<Props> = memo(({ language, value }) => {}const fileExtension = programmingLanguages[language] || '.file'const suggestedFileName = `file-${generateId()}${fileExtension}`- const fileName = window.prompt('Enter file name' || '', suggestedFileName)+ const fileName = window.prompt('Enter file name', suggestedFileName)if (!fileName) {// User pressed cancel on prompt.diff --git a/package.json b/package.jsonindex 938a698c..702f5815 100644--- a/package.json+++ b/package.json@@ -41,7 +41,8 @@"next-themes": "^0.3.0","node-html-parser": "^6.1.13","ollama-ai-provider": "^1.1.0",- "react-dom": "^18",+ "react": "^19.0.0",+ "react-dom": "^19.0.0","react-icons": "^5.0.1","react-markdown": "^8.0.7","react-syntax-highlighter": "^15.5.0",