Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Chore/more server actions (#19379)

Jonathan Summers-Muir7abc9d24c4a1
diff --git a/apps/database-new/app/LoadingLine.tsx b/apps/database-new/app/LoadingLine.tsx
new file mode 100644
index 00000000000..3f19ddc1a5c
--- /dev/null
+++ b/apps/database-new/app/LoadingLine.tsx
@@ -0,0 +1,20 @@
+'use client'
+
+import { useAppStateSnapshot } from '@/lib/state'
+import { usePathname, useParams } from 'next/navigation'
+import { LoadingLine as LoadingLineComponent } from 'ui'
+
+function LoadingLine() {
+ const snap = useAppStateSnapshot()
+ const params = useParams()
+ const pathName = usePathname()
+
+ const runId = params.runId as string
+
+ const loading =
+ runId && snap.runsLoading.includes(runId) && pathName.includes(runId) ? true : false
+
+ return <LoadingLineComponent loading={loading} />
+}
+
+export { LoadingLine }
diff --git a/apps/database-new/app/NewThreadInput.tsx b/apps/database-new/app/NewThreadInput.tsx
index 19756ad519c..7549eef52b0 100644
--- a/apps/database-new/app/NewThreadInput.tsx
+++ b/apps/database-new/app/NewThreadInput.tsx
@@ -4,14 +4,16 @@ import { CHAT_EXAMPLES } from '@/data/chat-examples'
import { useAppStateSnapshot } from '@/lib/state'
import { createClient } from '@/lib/supabase/client'
import { ExternalLink } from 'lucide-react'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { useFormState } from 'react-dom'
import { AssistantChatForm, cn } from 'ui'
-import { updateThread } from './actions'
+import { createThread } from './actions'
+import { useRouter } from 'next/navigation'
const suggestions = CHAT_EXAMPLES
const NewThreadInput = () => {
+ const router = useRouter()
const [value, setValue] = useState(() => {
if (typeof window !== 'undefined') {
const localPrompt = localStorage.getItem('prompt')
@@ -28,10 +30,25 @@ const NewThreadInput = () => {
success: undefined,
data: {
value,
+ runId: undefined,
+ threadId: undefined,
+ messageId: undefined,
},
}
- const [state, formAction] = useFormState(updateThread, initialState)
+ const [state, formAction] = useFormState(createThread, initialState)
+
+ // useEffect(() => {
+ // if (state.success && state.data.threadId && state.data.runId && state.data.messageId) {
+ // console.log(state.data)
+ // const { threadId, runId, messageId } = state.data
+ // console.log('threadId', threadId)
+ // console.log('runId', runId)
+ // console.log('messageId', messageId)
+ // // router.push(`/${state.data.threadId}/${state.data.runId}/${state.data.messageId}`)
+ // }
+ // }, [state.success])
+
const supabase = createClient()
const snap = useAppStateSnapshot()
@@ -43,7 +60,6 @@ const NewThreadInput = () => {
key={'new-thread-form'}
id={'new-thread-form'}
onSubmit={async (event) => {
- console.log('hello')
const {
data: { user },
} = await supabase.auth.getUser()
@@ -57,8 +73,9 @@ const NewThreadInput = () => {
value={value}
placeholder="e.g Create a Telegram-like chat application"
onValueChange={(e) => setValue(e.target.value)}
- message={state.message}
+ message={state?.message}
/>
+ {state?.message && <p>{state?.message}</p>}
</div>
<div className="flex gap-3">
{suggestions.map((suggestion, idx) => (
diff --git a/apps/database-new/app/[threadId]/Chat.tsx b/apps/database-new/app/[threadId]/Chat.tsx
deleted file mode 100644
index 7ebdaffeed2..00000000000
--- a/apps/database-new/app/[threadId]/Chat.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-'use client'
-
-import { useMutation } from '@tanstack/react-query'
-import { sortBy } from 'lodash'
-import { Loader2 } from 'lucide-react'
-import { useParams, useRouter } from 'next/navigation'
-import { FormEventHandler, useEffect, useMemo, useState } from 'react'
-import { AssistantChatForm, ScrollArea, cn } from 'ui'
-
-import { useMessagesQuery } from '@/data/messages-query'
-import { AssistantMessage, UserMessage } from '@/lib/types'
-import BottomMarker from './BottomMarker'
-import UserChat from './UserChat'
-
-export const Chat = () => {
- const router = useRouter()
- const [value, setValue] = useState('')
- const [inputEntered, setInputEntered] = useState(false)
- const { threadId, runId, messageId }: { threadId: string; runId: string; messageId: string } =
- useParams()
-
- const { data, isSuccess } = useMessagesQuery({ threadId, runId })
-
- const messages = useMemo(() => {
- if (isSuccess) return sortBy(data.messages, (m) => m.created_at)
- return []
- }, [data?.messages, isSuccess])
-
- const selectedMessage = messageId
- const loading = isSuccess && data.status === 'loading'
- const userMessages = messages.filter((message) => message.role === 'user')
-
- const { mutate } = useMutation({
- mutationFn: async (prompt: string) => {
- const body = { prompt }
- const response = await fetch(`/api/ai/sql/threads/${threadId}/update`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- })
-
- const result = await response.json()
- return result
- },
- onSuccess(data) {
- const url = messageId
- ? `/${data.threadId}/${data.runId}/${messageId}`
- : `/${data.threadId}/${data.runId}`
- router.push(url)
- },
- })
-
- useEffect(() => {
- setInputEntered(false)
- setValue('')
- }, [loading])
-
- return (
- <div
- className={cn(
- 'bg',
- 'h-full',
- 'border-t xl:border-t-0 xl:border-r relative',
- 'flex flex-col h-full border-r',
- 'w-full xl:w-[400px] 2xl:w-[500px]'
- )}
- >
- <div className="flex flex-col grow items-between">
- {messages.length === 0 ? (
- <div className="grow flex items-center justify-center">
- <Loader2 className="animate-spin" />
- </div>
- ) : (
- <ScrollArea className="grow h-px">
- <div className="flex flex-col py-2 xl:py-6">
- {userMessages.map((message, idx) => {
- const index = messages.indexOf(message)
- const reply = messages[index + 1] as AssistantMessage
- const isLatest = idx === userMessages.length - 1
- return (
- <UserChat
- key={message.id}
- message={message as UserMessage}
- reply={reply}
- isLatest={isLatest}
- isSelected={selectedMessage === message?.id}
- isLoading={loading && isLatest}
- />
- )
- })}
- <BottomMarker />
- </div>
- </ScrollArea>
- )}
-
- <div className="px-4 pb-4">
- <AssistantChatForm
- key={`chat-thread-form-${runId}`}
- id={`chat-thread-form-${runId}`}
- onSubmit={async (event) => {
- event.preventDefault()
- mutate(value)
- }}
- value={value}
- disabled={loading || inputEntered}
- loading={loading || inputEntered}
- placeholder={
- loading
- ? 'Generating reply to request...'
- : 'Ask for some changes on the selected message'
- }
- onValueChange={(v) => setValue(v.target.value)}
- />
- </div>
- </div>
- </div>
- )
-}
diff --git a/apps/database-new/app/[threadId]/BottomMarker.tsx b/apps/database-new/app/[threadId]/[runId]/BottomMarker.tsx
similarity index 65%
rename from apps/database-new/app/[threadId]/BottomMarker.tsx
rename to apps/database-new/app/[threadId]/[runId]/BottomMarker.tsx
index 7e5cbf31704..1231218a54c 100644
--- a/apps/database-new/app/[threadId]/BottomMarker.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/BottomMarker.tsx
@@ -1,7 +1,9 @@
-import { useEffect, useRef } from 'react'
+'use client'
+
+import { createRef, useEffect } from 'react'
const BottomMarker = () => {
- const ref = useRef<HTMLDivElement>(null)
+ const ref = createRef<HTMLDivElement>()
useEffect(() => {
if (ref.current) {
@@ -14,4 +16,4 @@ const BottomMarker = () => {
return <div ref={ref} />
}
-export default BottomMarker
+export { BottomMarker }
diff --git a/apps/database-new/app/[threadId]/[runId]/Chat.tsx b/apps/database-new/app/[threadId]/[runId]/Chat.tsx
new file mode 100644
index 00000000000..f4aafefba87
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/Chat.tsx
@@ -0,0 +1,36 @@
+import { Suspense } from 'react'
+import { ScrollArea } from 'ui'
+
+import { cn } from '@ui/lib/utils/cn'
+
+import { Messages } from './Messages'
+import { ChatInput } from './ChatInput'
+import { BottomMarker } from './BottomMarker'
+
+async function Chat({ params }: { params: { threadId: string; runId: string } }) {
+ return (
+ <div
+ className={cn(
+ 'bg',
+ 'h-full',
+ 'border-t xl:border-t-0 xl:border-r relative',
+ 'flex flex-col h-full border-r',
+ 'w-full xl:w-[400px] 2xl:w-[500px]'
+ )}
+ >
+ <div className="flex flex-col grow items-between">
+ <ScrollArea className="grow h-px">
+ <div className="flex flex-col py-2 xl:py-6">
+ <Suspense fallback={<p> loading</p>}>
+ <Messages params={params} />
+ </Suspense>
+ <BottomMarker />
+ </div>
+ </ScrollArea>
+ <ChatInput params={params} />
+ </div>
+ </div>
+ )
+}
+
+export { Chat }
diff --git a/apps/database-new/app/[threadId]/[runId]/ChatInput.tsx b/apps/database-new/app/[threadId]/[runId]/ChatInput.tsx
new file mode 100644
index 00000000000..2678473deae
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/ChatInput.tsx
@@ -0,0 +1,60 @@
+'use client'
+
+import { updateThread } from '@/app/actions'
+import { useState } from 'react'
+import { useFormState, useFormStatus } from 'react-dom'
+import { AssistantChatForm, Input } from 'ui'
+
+function ChatInput({ params }: { params: { threadId: string; runId: string } }) {
+ const [value, setValue] = useState('')
+
+ const { threadId, runId } = params
+
+ const initialState = {
+ message: undefined,
+ success: undefined,
+ data: {
+ value,
+ },
+ }
+
+ const [state, formAction] = useFormState(updateThread, initialState)
+
+ const Message = () => {
+ const { pending } = useFormStatus()
+
+ return !state.success && state.success !== undefined && !pending ? (
+ <p className="text-xs text-warning text-center w-full p-3">{state.message}</p>
+ ) : null
+ }
+
+ return (
+ <div className="px-4 pb-4">
+ <AssistantChatForm
+ action={formAction}
+ key={`chat-thread-form-${runId}`}
+ id={`chat-thread-form-${runId}`}
+ value={value}
+ placeholder={
+ // loading
+ // ? 'Generating reply to request...'
+ // :
+ 'Ask for some changes on the selected message'
+ }
+ onValueChange={(v) => setValue(v.target.value)}
+ message={state.message}
+ >
+ <Input
+ type="hidden"
+ name="threadId"
+ value={threadId}
+ key={`chat-thread-form-${threadId}`}
+ />
+ <Input type="hidden" name="runId" value={runId} key={`chat-thread-form-${runId}}`} />
+ </AssistantChatForm>
+ <Message />
+ </div>
+ )
+}
+
+export { ChatInput }
diff --git a/apps/database-new/app/[threadId]/[runId]/Messages.tsx b/apps/database-new/app/[threadId]/[runId]/Messages.tsx
new file mode 100644
index 00000000000..c4fb282dd94
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/Messages.tsx
@@ -0,0 +1,56 @@
+import dayjs from 'dayjs'
+import relativeTime from 'dayjs/plugin/relativeTime'
+import { sortBy } from 'lodash'
+import OpenAI from 'openai'
+import UserChat from './UserChat'
+
+dayjs.extend(relativeTime)
+
+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
+
+async function Messages({ params }: { params: { threadId: string; runId: string } }) {
+ const [run, { data: messages }] = await Promise.all([
+ openai.beta.threads.runs.retrieve(params.threadId, params.runId),
+ openai.beta.threads.messages.list(params.threadId),
+ ])
+
+ const messagesSorted = sortBy(messages, (m) => m.created_at)
+
+ const userMessages = messagesSorted.filter((message) => message.role === 'user')
+
+ return (
+ <div className="flex flex-col py-2 xl:py-6">
+ {userMessages.map((message, idx) => {
+ const index = messages.indexOf(message)
+
+ const reply = messages[index + 1]
+ const isLatest = idx === userMessages.length - 1
+
+ const hoursFromNow = dayjs().diff(dayjs(message.created_at * 1000), 'hours')
+ const formattedTimeFromNow = dayjs(message.created_at * 1000).fromNow()
+ const formattedCreatedAt = dayjs(message.created_at * 1000).format('DD MMM YYYY, HH:mm')
+ const replyDuration =
+ reply !== undefined ? reply.created_at - message.created_at : undefined
+
+ const times = {
+ hoursFromNow,
+ formattedTimeFromNow,
+ formattedCreatedAt,
+ replyDuration,
+ }
+
+ return (
+ <UserChat
+ key={message.id}
+ message={message}
+ run={run}
+ isLatest={isLatest}
+ times={times}
+ />
+ )
+ })}
+ </div>
+ )
+}
+
+export { Messages }
diff --git a/apps/database-new/app/[threadId]/UserChat.tsx b/apps/database-new/app/[threadId]/[runId]/UserChat.tsx
similarity index 61%
rename from apps/database-new/app/[threadId]/UserChat.tsx
rename to apps/database-new/app/[threadId]/[runId]/UserChat.tsx
index 652aae684c6..bb5c3e09a68 100644
--- a/apps/database-new/app/[threadId]/UserChat.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/UserChat.tsx
@@ -1,27 +1,60 @@
+'use client'
+
+import { useAppStateSnapshot } from '@/lib/state'
import { AssistantMessage, UserMessage } from '@/lib/types'
-import dayjs from 'dayjs'
-import relativeTime from 'dayjs/plugin/relativeTime'
-import { useParams, useRouter } from 'next/navigation'
+import { useParams, usePathname, useRouter } from 'next/navigation'
+import OpenAI from 'openai'
import { cn } from 'ui'
-
-dayjs.extend(relativeTime)
+import { pull } from 'lodash'
+import { useEffect } from 'react'
interface UserChatProps {
- message: UserMessage
- reply?: AssistantMessage
+ message: OpenAI.Beta.Threads.Messages.ThreadMessage
isLatest: boolean
- isSelected: boolean
- isLoading: boolean
+ times: {
+ hoursFromNow: number
+ formattedTimeFromNow: string
+ formattedCreatedAt: string
+ replyDuration: number | undefined
+ }
+ run: OpenAI.Beta.Threads.Run
}
-const UserChat = ({ message, reply, isLatest, isSelected, isLoading }: UserChatProps) => {
+const UserChat = ({ message, isLatest, times, run }: UserChatProps) => {
const router = useRouter()
+ const snap = useAppStateSnapshot()
const { threadId, runId } = useParams()
- const hoursFromNow = dayjs().diff(dayjs(message.created_at * 1000), 'hours')
- const formattedTimeFromNow = dayjs(message.created_at * 1000).fromNow()
- const formattedCreatedAt = dayjs(message.created_at * 1000).format('DD MMM YYYY, HH:mm')
- const replyDuration = reply !== undefined ? reply.created_at - message.created_at : undefined
+ // console.log(run)
+
+ const LOADING_STATUSES = ['in_progress', 'queued']
+
+ const runIsInProgressRemotely = LOADING_STATUSES.includes(run.status)
+
+ useEffect(() => {
+ if (runIsInProgressRemotely) {
+ // set a local state for run loading
+ // this state will be updated via other client components when completing a run
+ // remove current message id from array if it exists
+ let currentRunsLoading = [...snap.runsLoading]
+ pull(currentRunsLoading, run.id)
+ const payload = [...currentRunsLoading, run.id]
+ snap.setRunsLoading([...payload])
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [runIsInProgressRemotely, run.id]) // Intentionally left snap out of the dependency array
+
+ // using the local state for run loading
+ const isLoading = snap.runsLoading.includes(run.id) && isLatest
+
+ const { hoursFromNow, formattedTimeFromNow, formattedCreatedAt, replyDuration } = times
+
+ // chat shown as selected when url matches
+ const isSelected = usePathname().includes(message.id)
+
+ // extract the text from the assistant message
+ const message_content = message.content[0]
+ const text = message_content.type === 'text' ? message_content.text.value : ''
return (
<div
@@ -76,24 +109,24 @@ const UserChat = ({ message, reply, isLatest, isSelected, isLoading }: UserChatP
</svg>
</span>
<div
- title={message.text}
+ title={text}
className={cn(
'cursor-pointer transition relative overflow-hidden',
'w-full rounded-lg rounded-tl-none',
'bg-alternative',
- 'border'
- // isSelected ? 'bg-surface-100' : 'bg-surface-100 group-hover:bg-surface-200'
+ 'border',
+ isSelected ? 'bg-surface-100' : 'bg-surface-100 group-hover:bg-surface-200'
)}
>
<p
className={cn(
- 'transition p-4 text-sm',
+ 'transition p-4 text-xs',
isSelected ? 'text-foreground' : 'text-light group-hover:text-foreground'
)}
>
- {message.text}
+ {text}
</p>
- {isLoading && <div className="chat-shimmering-loader w-full h-0.5 absolute bottom-0" />}
+ {/* {isLoading && <div className="chat-shimmering-loader w-full h-0.5 absolute bottom-0" />} */}
</div>
</div>
{isSelected && (
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx
index 31c7c550088..6cbaa06cfab 100644
--- a/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx
@@ -4,13 +4,35 @@ import { getThread } from './MessageId.utils'
import { MonacoEditor } from './MonacoEditor'
import { CodeEditorContainer } from './CodeEditorContainer'
+import OpenAI from 'openai'
+
+const openai = new OpenAI()
+
+async function waitForRunCompletion(params: { threadId: string; runId: string }) {
+ console.log('waiting for run completion')
+ let realRun = await openai.beta.threads.runs.retrieve(params.threadId, params.runId)
+
+ while (realRun.status === 'in_progress') {
+ console.log('while..')
+ await new Promise((resolve) => setTimeout(resolve, 2000))
+ realRun = await openai.beta.threads.runs.retrieve(params.threadId, params.runId)
+ console.log('realRun', realRun.status)
+ }
+
+ console.log('Run completed:', realRun.status)
+}
+
export async function CodeEditor({ params }: { params: any }) {
const { threadId, runId, messageId } = params
+ await waitForRunCompletion(params)
+
const content = await getThread({ threadId, runId, messageId })
const code = format(content, { language: 'postgresql' })
+ // keep polling until the run is completed
+
// useEffect(() => {
// snap.setSelectedCode(code)
// }, [code])
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts b/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts
index 73e2ef4ccb1..8d70888c5ed 100644
--- a/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts
@@ -16,6 +16,8 @@ async function getThread({
runId: string
messageId: string
}) {
+ console.log('getting thread..', threadId, runId, messageId)
+
const [run, { data: _messages }] = await Promise.all([
openai.beta.threads.runs.retrieve(threadId, runId),
openai.beta.threads.messages.list(threadId),
@@ -51,7 +53,7 @@ async function getThread({
messages = sortBy(messages, (m) => m.created_at)
- const userMessages = messages.filter((m) => m.role === 'user')
+ // const userMessages = messages.filter((m) => m.role === 'user')
const selectedMessageIdx = messages.findIndex((m) => m.id === messageId)
const selectedMessageReply = (
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx
index d85a1c3859e..0e46d182693 100644
--- a/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx
@@ -1,22 +1,43 @@
-import { format } from 'sql-formatter'
-
import { getThread } from './MessageId.utils'
import { parseTables } from '@/lib/utils'
import SchemaFlowHandler from './SchemaFlowHandler'
+import OpenAI from 'openai'
+
+const openai = new OpenAI()
+
+async function waitForRunCompletion(params: {
+ threadId: string
+ runId: string
+ messageId: string
+}) {
+ let realRun = await openai.beta.threads.runs.retrieve(params.threadId, params.runId)
+
+ while (realRun.status === 'in_progress') {
+ console.log('while.. waiting for in_progress status to change for ', params.runId)
+ await new Promise((resolve) => setTimeout(resolve, 2000))
+ realRun = await openai.beta.threads.runs.retrieve(params.threadId, params.runId)
+ console.log('realRun', realRun.status)
+ }
+
+ console.log('Run completed:', realRun.status)
+ return
+}
+
export async function SchemaFlow({ params }: { params: any }) {
const { threadId, runId, messageId } = params
+ // keep polling until the run is completed
+ await waitForRunCompletion(params)
+
const content = await getThread({ threadId, runId, messageId })
// const code = format(content, { language: 'postgresql' })
- const tables = await parseTables(content)
-
// useEffect(() => {
// snap.setSelectedCode(code)
// }, [code])
- return <SchemaFlowHandler tables={tables} />
+ return <SchemaFlowHandler content={content} />
}
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
index 80c2e7dad6e..866f5f2f7fc 100644
--- a/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
@@ -1,4 +1,5 @@
'use client'
+
import { PostgresTable } from '@/lib/types'
import { useTheme } from 'next-themes'
import { useEffect, useMemo, useState } from 'react'
@@ -13,19 +14,37 @@ import { cn } from 'ui'
import { getGraphDataFromTables } from './SchemaFlow.utils'
import TableNode from './TableNode'
+import { useAppStateSnapshot } from '@/lib/state'
+import { useParams } from 'next/navigation'
+import { set } from 'lodash'
+import { parseTables } from '@/lib/utils'
interface SchemaGraphProps {
- tables: PostgresTable[]
+ tables?: PostgresTable[]
+ content: any
}
-const SchemaFlowHandler = ({ tables }: SchemaGraphProps) => {
+const SchemaFlowHandler = ({ content }: SchemaGraphProps) => {
const { resolvedTheme } = useTheme()
const [mounted, setMounted] = useState(false)
+ const [tables, setTables] = useState<PostgresTable[]>([])
const reactFlowInstance = useReactFlow()
const nodeTypes = useMemo(() => ({ table: TableNode }), [])
useEffect(() => {
setMounted(true)
+
+ const parseTableData = async () => {
+ try {
+ const tables = await parseTables(content)
+ setTables(tables)
+ } catch (error) {
+ // Handle errors
+ console.log('error', error)
+ }
+ }
+
+ parseTableData() // Call the async function
}, [])
useEffect(() => {
@@ -34,7 +53,7 @@ const SchemaFlowHandler = ({ tables }: SchemaGraphProps) => {
reactFlowInstance.setEdges(edges)
setTimeout(() => reactFlowInstance.fitView({}), 10)
})
- }, [tables, resolvedTheme])
+ }, [tables, resolvedTheme, reactFlowInstance])
return (
<>
@@ -73,10 +92,25 @@ const SchemaFlowHandler = ({ tables }: SchemaGraphProps) => {
)
}
-const ExportedSchemaGraph = ({ tables }: SchemaGraphProps) => {
+const ExportedSchemaGraph = ({ content }: SchemaGraphProps) => {
+ const snap = useAppStateSnapshot()
+ const params = useParams()
+
+ const runId = params.runId as string
+
+ useEffect(() => {
+ const runIsLoading = snap.runsLoading.includes(runId)
+ if (runIsLoading) {
+ // let currentRunsLoading = snap.runsLoading
+ const payload = [...snap.runsLoading.filter((item) => item !== runId)]
+ snap.setRunsLoading([...payload])
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [runId]) // Intentionally left snap out of the dependency array
+
return (
<ReactFlowProvider>
- <SchemaFlowHandler tables={tables} />
+ <SchemaFlowHandler content={content} />
</ReactFlowProvider>
)
}
diff --git a/apps/database-new/app/[threadId]/layout.tsx b/apps/database-new/app/[threadId]/[runId]/layout.tsx
similarity index 61%
rename from apps/database-new/app/[threadId]/layout.tsx
rename to apps/database-new/app/[threadId]/[runId]/layout.tsx
index 85b76e12e95..0c89c941fad 100644
--- a/apps/database-new/app/[threadId]/layout.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/layout.tsx
@@ -1,12 +1,20 @@
-'use client'
-import { Chat } from '@/app/[threadId]/Chat'
+import { Chat } from '@/app/[threadId]/[runId]/Chat'
import SaveSchemaDropdown from '@/components/Header/SaveSchemaDropdown'
import ToggleCodeEditorButton from '@/components/Header/ToggleCodeEditorButton'
+import { threadId } from 'worker_threads'
+
+export default function Layout({
+ children,
+ params,
+}: {
+ children: React.ReactNode
+ params: { threadId: string; runId: string }
+}) {
+ console.log('revalidating layout of runid')
-export default function Layout({ children }: { children: React.ReactNode }) {
return (
<div className="flex flex-col-reverse items-between xl:flex-row xl:items-center xl:justify-between bg-alternative h-full">
- <Chat />
+ <Chat params={params} />
<div className="xl:hidden flex items-center gap-x-2 justify-end border-t py-2 px-2 bg-background">
<ToggleCodeEditorButton />
<SaveSchemaDropdown />
diff --git a/apps/database-new/app/[threadId]/[runId]/page.tsx b/apps/database-new/app/[threadId]/[runId]/page.tsx
index e4c38f97b41..7e981433fe3 100644
--- a/apps/database-new/app/[threadId]/[runId]/page.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/page.tsx
@@ -1,33 +1,7 @@
-'use client'
+import * as React from 'react'
-import { last, sortBy } from 'lodash'
-import { useParams, useRouter } from 'next/navigation'
-import { useEffect, useMemo } from 'react'
-
-import { useMessagesQuery } from '@/data/messages-query'
-
-export default function ThreadPage() {
- const router = useRouter()
- const { threadId, runId }: { threadId: string; runId: string } = useParams()
-
- const { data, isSuccess } = useMessagesQuery({ threadId, runId })
-
- const messages = useMemo(() => {
- if (isSuccess) return sortBy(data.messages, (m) => m.created_at)
- return []
- }, [data?.messages, isSuccess])
-
- useEffect(() => {
- if (isSuccess && messages.length > 0) {
- const latestMessage = last(messages.filter((message) => message.role === 'user'))
- if (latestMessage) router.push(`/${threadId}/${runId}/${latestMessage.id}`)
- }
- }, [isSuccess])
-
- return (
- <div className="grow max-h-screen flex flex-row items-center justify-between bg-alternative h-full">
- {/* <SchemaGraph tables={[]} />
- <CodeEditor content="" /> */}
- </div>
- )
+const RunIdPage = async () => {
+ return <></>
}
+
+export default RunIdPage
diff --git a/apps/database-new/app/actions.ts b/apps/database-new/app/actions.ts
index 69602421433..ef53dad1bad 100644
--- a/apps/database-new/app/actions.ts
+++ b/apps/database-new/app/actions.ts
@@ -8,7 +8,7 @@ import { parseTables } from '@/lib/utils'
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
-import { redirect } from 'next/navigation'
+import { RedirectType, redirect } from 'next/navigation'
import OpenAI from 'openai'
import { z } from 'zod'
@@ -101,7 +101,7 @@ export async function updateThreadName(prevState: any, formData: FormData) {
}
}
-export async function updateThread(prevState: any, formData: FormData) {
+export async function createThread(prevState: any, formData: FormData) {
const cookieStore = cookies()
const supabase = createClient(cookieStore)
@@ -131,7 +131,7 @@ export async function updateThread(prevState: any, formData: FormData) {
const thread = await openai.beta.threads.create()
- await openai.beta.threads.messages.create(thread.id, {
+ const message = await openai.beta.threads.messages.create(thread.id, {
role: 'user',
content: data.value,
})
@@ -156,7 +156,6 @@ export async function updateThread(prevState: any, formData: FormData) {
.find((text) => text !== undefined)
try {
- console.log('inserting thread')
const { error } = await supabase.from('threads').insert({
thread_id: thread.id,
run_id: run.id,
@@ -169,7 +168,16 @@ export async function updateThread(prevState: any, formData: FormData) {
console.error(error)
}
- redirectUrl = `/${thread.id}/${run.id}`
+ redirectUrl = `/${thread.id}/${run.id}/${message.id}`
+ // return {
+ // success: true,
+ // message: 'Managed to run action',
+ // data: {
+ // messageId: message.id,
+ // runId: run.id,
+ // threadId: thread.id,
+ // },
+ // }
} catch (error: any) {
console.error(error)
return {
@@ -181,3 +189,48 @@ export async function updateThread(prevState: any, formData: FormData) {
redirect(redirectUrl)
}
+
+export async function updateThread(prevState: any, formData: FormData) {
+ const cookieStore = cookies()
+ const supabase = createClient(cookieStore)
+
+ let redirectUrl = ''
+
+ try {
+ const schema = z.object({
+ value: z.string(),
+ threadId: z.string(),
+ runId: z.string(),
+ })
+
+ const data = schema.parse({
+ value: formData.get('value'),
+ threadId: formData.get('threadId'),
+ runId: formData.get('runId'),
+ })
+
+ const message = await openai.beta.threads.messages.create(data.threadId, {
+ content: data.value,
+ role: 'user',
+ })
+
+ revalidatePath(`/${data.threadId}/${data.runId}`, 'layout')
+
+ const run = await openai.beta.threads.runs.create(message.thread_id, {
+ assistant_id: 'asst_oLWrK8lScZVNEpfjwUIvBAnq',
+ })
+
+ revalidatePath(`/${data.threadId}/${data.runId}/${message.id}`, 'layout')
+
+ redirectUrl = `/${message.thread_id}/${run.id}/${message.id}`
+ } catch (error: any) {
+ return {
+ success: false,
+ message: 'Failed to update schema with new prompt',
+ data: undefined,
+ }
+ }
+
+ revalidatePath(redirectUrl)
+ redirect(redirectUrl)
+}
diff --git a/apps/database-new/app/layout.tsx b/apps/database-new/app/layout.tsx
index 1f61a9104e6..2b3f8c5b0f0 100644
--- a/apps/database-new/app/layout.tsx
+++ b/apps/database-new/app/layout.tsx
@@ -2,9 +2,10 @@ import '@ui/layout/ai-icon-animation/ai-icon-animation-style.module.css'
import './globals.css'
import Header from '@/components/Header/Header'
-import { ReactQueryProvider, ThemeProvider } from '@/components/providers'
+import { ThemeProvider } from '@/components/providers'
import type { Metadata } from 'next'
import Footer from '@/components/Footer'
+import { LoadingLine } from './LoadingLine'
const defaultUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
@@ -23,13 +24,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<html lang="en" className="dark h-full bg-background" suppressHydrationWarning>
<body className="flex flex-col h-full">
<ThemeProvider defaultTheme="system" enableSystem disableTransitionOnChange>
- <ReactQueryProvider>
- <Header />
- <main role="main" className="h-full w-full flex flex-col grow">
- {children}
- </main>
- <Footer />
- </ReactQueryProvider>
+ <Header />
+ <LoadingLine />
+ <main role="main" className="h-full w-full flex flex-col grow">
+ {children}
+ </main>
+ <Footer />
</ThemeProvider>
</body>
</html>
diff --git a/apps/database-new/app/page.tsx b/apps/database-new/app/page.tsx
index ef35eccdf6a..68c3f25db35 100644
--- a/apps/database-new/app/page.tsx
+++ b/apps/database-new/app/page.tsx
@@ -1,7 +1,8 @@
-import LoginForm from '@/components/Auth/LoginForm'
+// import LoginForm from '@/components/Auth/LoginForm'
import type { Metadata } from 'next'
import { LoginDialog } from './LoginDialog'
import NewThreadInput from './NewThreadInput'
+import LoginForm from '@/components/Auth/LoginForm'
export const metadata: Metadata = {
title: 'database.design | Create',
diff --git a/apps/database-new/components/AllThreadsModal/AllThreadsModal.tsx b/apps/database-new/components/AllThreadsModal/AllThreadsModal.tsx
index 3d1fdf7f8de..ad988bf4164 100644
--- a/apps/database-new/components/AllThreadsModal/AllThreadsModal.tsx
+++ b/apps/database-new/components/AllThreadsModal/AllThreadsModal.tsx
@@ -1,127 +1,127 @@
-'use client'
+// 'use client'
-import { useQuery } from '@tanstack/react-query'
-import { Modal } from 'ui'
-import { useParams } from 'next/navigation'
-import { AssistantMessage, ReadThreadAPIResult, UserMessage } from '@/lib/types'
-import { useEffect, useMemo } from 'react'
-import { sortBy } from 'lodash'
-import ReactFlow, {
- Background,
- BackgroundVariant,
- ReactFlowProvider,
- useReactFlow,
- MiniMap,
-} from 'reactflow'
-import { getGraphDataFromMessages } from './AllThreadsModal.utils'
-import MessageNode from './MessageNode'
+// import { useQuery } from '@tanstack/react-query'
+// import { Modal } from 'ui'
+// import { useParams } from 'next/navigation'
+// import { AssistantMessage, ReadThreadAPIResult, UserMessage } from '@/lib/types'
+// import { useEffect, useMemo } from 'react'
+// import { sortBy } from 'lodash'
+// import ReactFlow, {
+// Background,
+// BackgroundVariant,
+// ReactFlowProvider,
+// useReactFlow,
+// MiniMap,
+// } from 'reactflow'
+// import { getGraphDataFromMessages } from './AllThreadsModal.utils'
+// import MessageNode from './MessageNode'
-interface AllThreadsProps {
- visible: boolean
- onClose: () => void
- onSelectMessage: (messageId: string, replyId: string) => void
-}
+// interface AllThreadsProps {
+// visible: boolean
+// onClose: () => void
+// onSelectMessage: (messageId: string, replyId: string) => void
+// }
-// [Joshen] POC idea for forking/branching - not for phase 1
+// // [Joshen] POC idea for forking/branching - not for phase 1
-const AllThreads = ({ visible, onClose, onSelectMessage }: AllThreadsProps) => {
- const params = useParams()
- const reactFlowInstance = useReactFlow()
- const nodeTypes = useMemo(() => ({ message: MessageNode }), [])
+// const AllThreads = ({ visible, onClose, onSelectMessage }: AllThreadsProps) => {
+// const params = useParams()
+// const reactFlowInstance = useReactFlow()
+// const nodeTypes = useMemo(() => ({ message: MessageNode }), [])
- // [Joshen] Scaffolding a query cause im presuming we need a different endpoint to retrieve _all_ threads
- const { data, isSuccess } = useQuery<ReadThreadAPIResult>({
- queryFn: async () => {
- const response = await fetch(`/api/ai/sql/threads/${params.threadId}/read/${params.runId}`, {
- method: 'GET',
- })
+// // [Joshen] Scaffolding a query cause im presuming we need a different endpoint to retrieve _all_ threads
+// const { data, isSuccess } = useQuery<ReadThreadAPIResult>({
+// queryFn: async () => {
+// const response = await fetch(`/api/ai/sql/threads/${params.threadId}/read/${params.runId}`, {
+// method: 'GET',
+// })
- const result = await response.json()
- return result
- },
- queryKey: [params.threadId, params.runId],
- refetchInterval: (options) => {
- const data = options.state.data
- if (data && data.status === 'completed') {
- return Infinity
- }
- return 5000
- },
- enabled: !!(params.threadId && params.runId),
- })
+// const result = await response.json()
+// return result
+// },
+// queryKey: [params.threadId, params.runId],
+// refetchInterval: (options) => {
+// const data = options.state.data
+// if (data && data.status === 'completed') {
+// return Infinity
+// }
+// return 5000
+// },
+// enabled: !!(params.threadId && params.runId),
+// })
- const messages = useMemo(() => {
- if (isSuccess) return sortBy(data.messages, (m) => m.created_at)
- return []
- }, [data?.messages, isSuccess])
+// const messages = useMemo(() => {
+// if (isSuccess) return sortBy(data.messages, (m) => m.created_at)
+// return []
+// }, [data?.messages, isSuccess])
- const userMessages = messages.filter((m) => m.role === 'user') as UserMessage[]
+// const userMessages = messages.filter((m) => m.role === 'user') as UserMessage[]
- useEffect(() => {
- if (reactFlowInstance !== undefined && userMessages.length > 0) {
- const { nodes, edges } = getGraphDataFromMessages({
- messages: userMessages,
- onSelectMessage: (message: UserMessage) => {
- const index = messages.indexOf(message)
- const reply = messages[index + 1] as AssistantMessage
- onSelectMessage(message.id, reply.id)
- },
- })
- reactFlowInstance.setNodes(nodes)
- reactFlowInstance.setEdges(edges)
- setTimeout(() => {
- reactFlowInstance.fitView({})
- const viewport = reactFlowInstance.getViewport()
- reactFlowInstance.setViewport({ x: viewport.x - 70, y: 150, zoom: 1 })
- })
- }
- }, [reactFlowInstance, userMessages])
+// useEffect(() => {
+// if (reactFlowInstance !== undefined && userMessages.length > 0) {
+// const { nodes, edges } = getGraphDataFromMessages({
+// messages: userMessages,
+// onSelectMessage: (message: UserMessage) => {
+// const index = messages.indexOf(message)
+// const reply = messages[index + 1] as AssistantMessage
+// onSelectMessage(message.id, reply.id)
+// },
+// })
+// reactFlowInstance.setNodes(nodes)
+// reactFlowInstance.setEdges(edges)
+// setTimeout(() => {
+// reactFlowInstance.fitView({})
+// const viewport = reactFlowInstance.getViewport()
+// reactFlowInstance.setViewport({ x: viewport.x - 70, y: 150, zoom: 1 })
+// })
+// }
+// }, [reactFlowInstance, userMessages, messages, onSelectMessage])
- useEffect(() => {
- if (reactFlowInstance !== undefined && visible) {
- reactFlowInstance.fitView({})
- }
- }, [reactFlowInstance, visible])
+// useEffect(() => {
+// if (reactFlowInstance !== undefined && visible) {
+// reactFlowInstance.fitView({})
+// }
+// }, [reactFlowInstance, visible])
- return (
- <Modal
- showCloseButton
- hideFooter
- size="xxlarge"
- visible={visible}
- onCancel={onClose}
- header="All threads in current conversation"
- >
- <div className="h-[700px] border-t bg-background">
- <ReactFlow
- nodesDraggable={false}
- edgesUpdatable={false}
- defaultNodes={[]}
- defaultEdges={[]}
- maxZoom={1.1}
- nodeTypes={nodeTypes}
- proOptions={{ hideAttribution: true }}
- >
- <Background gap={16} color="#000" variant={BackgroundVariant.Lines} />
- <MiniMap
- pannable
- zoomable
- nodeColor={'rgba(0,0,0,0.7)'}
- maskColor={'rgba(0,0,0,0.85)'}
- className="border border-control rounded-md shadow-sm"
- />
- </ReactFlow>
- </div>
- </Modal>
- )
-}
+// return (
+// <Modal
+// showCloseButton
+// hideFooter
+// size="xxlarge"
+// visible={visible}
+// onCancel={onClose}
+// header="All threads in current conversation"
+// >
+// <div className="h-[700px] border-t bg-background">
+// <ReactFlow
+// nodesDraggable={false}
+// edgesUpdatable={false}
+// defaultNodes={[]}
+// defaultEdges={[]}
+// maxZoom={1.1}
+// nodeTypes={nodeTypes}
+// proOptions={{ hideAttribution: true }}
+// >
+// <Background gap={16} color="#000" variant={BackgroundVariant.Lines} />
+// <MiniMap
+// pannable
+// zoomable
+// nodeColor={'rgba(0,0,0,0.7)'}
+// maskColor={'rgba(0,0,0,0.85)'}
+// className="border border-control rounded-md shadow-sm"
+// />
+// </ReactFlow>
+// </div>
+// </Modal>
+// )
+// }
-const AllThreadsModal = ({ visible, onClose, onSelectMessage }: AllThreadsProps) => {
- return (
- <ReactFlowProvider>
- <AllThreads visible={visible} onClose={onClose} onSelectMessage={onSelectMessage} />
- </ReactFlowProvider>
- )
-}
+// const AllThreadsModal = ({ visible, onClose, onSelectMessage }: AllThreadsProps) => {
+// return (
+// <ReactFlowProvider>
+// <AllThreads visible={visible} onClose={onClose} onSelectMessage={onSelectMessage} />
+// </ReactFlowProvider>
+// )
+// }
-export default AllThreadsModal
+// export default AllThreadsModal
diff --git a/apps/database-new/components/AllThreadsModal/AllThreadsModal.utils.ts b/apps/database-new/components/AllThreadsModal/AllThreadsModal.utils.ts
index 02b9946b18f..7186a53d944 100644
--- a/apps/database-new/components/AllThreadsModal/AllThreadsModal.utils.ts
+++ b/apps/database-new/components/AllThreadsModal/AllThreadsModal.utils.ts
@@ -1,65 +1,65 @@
-import { UserMessage } from '@/lib/types'
-import dagre from '@dagrejs/dagre'
-import { Edge, Node, Position } from 'reactflow'
-import { NODE_HEIGHT, NODE_WIDTH } from './AllThreadsModal.constants'
-import { MessageNodeData } from './MessageNode'
+// import { UserMessage } from '@/lib/types'
+// import dagre from '@dagrejs/dagre'
+// import { Edge, Node, Position } from 'reactflow'
+// import { NODE_HEIGHT, NODE_WIDTH } from './AllThreadsModal.constants'
+// import { MessageNodeData } from './MessageNode'
-export const getGraphDataFromMessages = ({
- messages,
- onSelectMessage,
-}: {
- messages: UserMessage[]
- onSelectMessage: (message: UserMessage) => void
-}): { nodes: Node<MessageNodeData>[]; edges: Edge[] } => {
- const nodes: Node[] = messages.map((message, idx) => {
- return {
- id: message.id,
- type: 'message',
- data: {
- id: message.id,
- text: message.text,
- isStart: idx === 0,
- isEnd: idx === messages.length - 1,
- onSelectMessage: () => onSelectMessage(message),
- },
- position: { x: 0, y: 0 },
- }
- })
+// export const getGraphDataFromMessages = ({
+// messages,
+// onSelectMessage,
+// }: {
+// messages: UserMessage[]
+// onSelectMessage: (message: UserMessage) => void
+// }): { nodes: Node<MessageNodeData>[]; edges: Edge[] } => {
+// const nodes: Node[] = messages.map((message, idx) => {
+// return {
+// id: message.id,
+// type: 'message',
+// data: {
+// id: message.id,
+// text: message.text,
+// isStart: idx === 0,
+// isEnd: idx === messages.length - 1,
+// onSelectMessage: () => onSelectMessage(message),
+// },
+// position: { x: 0, y: 0 },
+// }
+// })
- const edges: Edge[] = []
- messages.forEach((message, idx) => {
- if (idx > 0) {
- edges.push({
- id: `edge-${idx}`,
- source: messages[idx - 1].id,
- target: message.id,
- type: 'smoothstep',
- animated: true,
- })
- }
- })
+// const edges: Edge[] = []
+// messages.forEach((message, idx) => {
+// if (idx > 0) {
+// edges.push({
+// id: `edge-${idx}`,
+// source: messages[idx - 1].id,
+// target: message.id,
+// type: 'smoothstep',
+// animated: true,
+// })
+// }
+// })
- const dagreGraph = new dagre.graphlib.Graph()
- dagreGraph.setDefaultEdgeLabel(() => ({}))
- dagreGraph.setGraph({ rankdir: 'TB', ranksep: 50, nodesep: 20 })
+// const dagreGraph = new dagre.graphlib.Graph()
+// dagreGraph.setDefaultEdgeLabel(() => ({}))
+// dagreGraph.setGraph({ rankdir: 'TB', ranksep: 50, nodesep: 20 })
- nodes.forEach((node) =>
- dagreGraph.setNode(node.id, { width: NODE_WIDTH / 2, height: NODE_HEIGHT / 2 })
- )
- edges.forEach((edge) => dagreGraph.setEdge(edge.source, edge.target))
- dagre.layout(dagreGraph)
+// nodes.forEach((node) =>
+// dagreGraph.setNode(node.id, { width: NODE_WIDTH / 2, height: NODE_HEIGHT / 2 })
+// )
+// edges.forEach((edge) => dagreGraph.setEdge(edge.source, edge.target))
+// dagre.layout(dagreGraph)
- nodes.forEach((node) => {
- const nodeWithPosition = dagreGraph.node(node.id)
- node.targetPosition = Position.Top
- node.sourcePosition = Position.Bottom
- node.position = {
- x: nodeWithPosition.x - nodeWithPosition.width / 2,
- y: nodeWithPosition.y - nodeWithPosition.height / 2,
- }
+// nodes.forEach((node) => {
+// const nodeWithPosition = dagreGraph.node(node.id)
+// node.targetPosition = Position.Top
+// node.sourcePosition = Position.Bottom
+// node.position = {
+// x: nodeWithPosition.x - nodeWithPosition.width / 2,
+// y: nodeWithPosition.y - nodeWithPosition.height / 2,
+// }
- return node
- })
+// return node
+// })
- return { nodes, edges }
-}
+// return { nodes, edges }
+// }
diff --git a/apps/database-new/components/AllThreadsModal/MessageNode.tsx b/apps/database-new/components/AllThreadsModal/MessageNode.tsx
index 50e90520d9b..4336aac3949 100644
--- a/apps/database-new/components/AllThreadsModal/MessageNode.tsx
+++ b/apps/database-new/components/AllThreadsModal/MessageNode.tsx
@@ -1,44 +1,44 @@
-import { Handle, NodeProps, Position } from 'reactflow'
-import { NODE_HEIGHT, NODE_WIDTH } from './AllThreadsModal.constants'
+// import { Handle, NodeProps, Position } from 'reactflow'
+// import { NODE_HEIGHT, NODE_WIDTH } from './AllThreadsModal.constants'
-export interface MessageNodeData {
- id: string
- text: string
- isStart: boolean
- isEnd: boolean
- onSelectMessage: () => void
-}
+// export interface MessageNodeData {
+// id: string
+// text: string
+// isStart: boolean
+// isEnd: boolean
+// onSelectMessage: () => void
+// }
-const MessageNode = ({ data }: NodeProps<MessageNodeData>) => {
- const { id, text, isStart, isEnd, onSelectMessage } = data
- return (
- <>
- {!isStart && (
- <Handle
- type="target"
- id="handle-t"
- position={Position.Top}
- style={{ background: 'transparent' }}
- />
- )}
- <div
- className="flex flex-col gap-y-1 rounded bg-surface-100 border border-default p-3 hover:bg-surface-200 transition cursor-pointer"
- style={{ width: NODE_WIDTH / 2 - 10, height: NODE_HEIGHT / 2 }}
- onClick={() => onSelectMessage()}
- >
- <p className="text-xs text-foreground-light font-mono">{id}</p>
- <p className="text-sm">{text}</p>
- </div>
- {!isEnd && (
- <Handle
- type="source"
- id="handle-s"
- position={Position.Bottom}
- style={{ background: 'transparent' }}
- />
- )}
- </>
- )
-}
+// const MessageNode = ({ data }: NodeProps<MessageNodeData>) => {
+// const { id, text, isStart, isEnd, onSelectMessage } = data
+// return (
+// <>
+// {!isStart && (
+// <Handle
+// type="target"
+// id="handle-t"
+// position={Position.Top}
+// style={{ background: 'transparent' }}
+// />
+// )}
+// <div
+// className="flex flex-col gap-y-1 rounded bg-surface-100 border border-default p-3 hover:bg-surface-200 transition cursor-pointer"
+// style={{ width: NODE_WIDTH / 2 - 10, height: NODE_HEIGHT / 2 }}
+// onClick={() => onSelectMessage()}
+// >
+// <p className="text-xs text-foreground-light font-mono">{id}</p>
+// <p className="text-sm">{text}</p>
+// </div>
+// {!isEnd && (
+// <Handle
+// type="source"
+// id="handle-s"
+// position={Position.Bottom}
+// style={{ background: 'transparent' }}
+// />
+// )}
+// </>
+// )
+// }
-export default MessageNode
+// export default MessageNode
diff --git a/apps/database-new/components/Auth/LoginForm.tsx b/apps/database-new/components/Auth/LoginForm.tsx
index 02849082c50..6cf20b367a7 100644
--- a/apps/database-new/components/Auth/LoginForm.tsx
+++ b/apps/database-new/components/Auth/LoginForm.tsx
@@ -2,7 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { Github } from 'lucide-react'
import { cookies, headers } from 'next/headers'
import { redirect } from 'next/navigation'
-import { Button } from 'ui'
+import { Button } from '@ui/components/Button'
export default function LoginForm({ searchParams }: { searchParams?: { message?: string } }) {
const signUp = async (formData: FormData) => {
diff --git a/apps/database-new/components/Footer.tsx b/apps/database-new/components/Footer.tsx
index 843fe15d1ef..c6d8cdb8665 100644
--- a/apps/database-new/components/Footer.tsx
+++ b/apps/database-new/components/Footer.tsx
@@ -9,10 +9,10 @@ export const links = [
]
const Footer = () => (
- <footer role="menu" className="border-t py-4 w-full px-4 flex justify-between">
- <ul className="flex items-center gap-4 text-xs">
+ <footer className="border-t py-4 w-full px-4 flex justify-between" role="contentinfo">
+ <ul className="flex items-center gap-4 text-xs" role="menu">
{links.map((link, index) => (
- <li key={index}>
+ <li key={index} role="menuitem">
<Link href={link.url}>{link.title}</Link>
</li>
))}
diff --git a/apps/database-new/components/Header/CurrentThreadName.tsx b/apps/database-new/components/Header/CurrentThreadName.tsx
index a89860593d5..14622d7c0b7 100644
--- a/apps/database-new/components/Header/CurrentThreadName.tsx
+++ b/apps/database-new/components/Header/CurrentThreadName.tsx
@@ -1,26 +1,27 @@
'use client'
import { useParams } from 'next/navigation'
-import { useMessagesQuery } from '@/data/messages-query'
-import { UserMessage } from '@/lib/types'
+// import { useMessagesQuery } from '@/data/messages-query'
+// import { UserMessage } from '@/lib/types'
const CurrentThreadName = () => {
- const { threadId, runId, messageId }: { threadId: string; runId: string; messageId: string } =
- useParams()
+ // const { threadId, runId, messageId }: { threadId: string; runId: string; messageId: string } =
+ // useParams()
- const isConversation = threadId !== undefined && runId !== undefined
+ // const isConversation = threadId !== undefined && runId !== undefined
- const { data } = useMessagesQuery({ threadId, runId, enabled: isConversation })
- const selectedMessage = data?.messages.find((m) => m.id === messageId) as UserMessage
+ // const { data } = useMessagesQuery({ threadId, runId, enabled: isConversation })
+ // const selectedMessage = data?.messages.find((m) => m.id === messageId) as UserMessage
return (
- <div className="hidden xl:block flex items-center gap-x-4">
- {selectedMessage !== undefined && (
- <p title={selectedMessage.text} className="truncate max-w-[700px] border-l text-sm px-4">
- {selectedMessage.text}
- </p>
- )}
- </div>
+ // <div className="hidden xl:block flex items-center gap-x-4">
+ // {selectedMessage !== undefined && (
+ // <p title={selectedMessage.text} className="truncate max-w-[700px] border-l text-sm px-4">
+ // {selectedMessage.text}
+ // </p>
+ // )}
+ // </div>
+ <></>
)
}
diff --git a/apps/database-new/components/Header/SaveSchemaDropdown.tsx b/apps/database-new/components/Header/SaveSchemaDropdown.tsx
index 981276459cc..6d46e5f9ef3 100644
--- a/apps/database-new/components/Header/SaveSchemaDropdown.tsx
+++ b/apps/database-new/components/Header/SaveSchemaDropdown.tsx
@@ -1,3 +1,5 @@
+'use client'
+
import { getAppStateSnapshot, useAppStateSnapshot } from '@/lib/state'
import Image from 'next/image'
import {
diff --git a/apps/database-new/components/Header/ToggleCodeEditorButton.tsx b/apps/database-new/components/Header/ToggleCodeEditorButton.tsx
index 36dbfe5ebc6..f9b1b986efb 100644
--- a/apps/database-new/components/Header/ToggleCodeEditorButton.tsx
+++ b/apps/database-new/components/Header/ToggleCodeEditorButton.tsx
@@ -1,3 +1,5 @@
+'use client'
+
import { useAppStateSnapshot } from '@/lib/state'
import { Button } from 'ui'
diff --git a/apps/database-new/components/Header/UserDropdown.tsx b/apps/database-new/components/Header/UserDropdown.tsx
index 0f8b571a525..03fbc9d62d8 100644
--- a/apps/database-new/components/Header/UserDropdown.tsx
+++ b/apps/database-new/components/Header/UserDropdown.tsx
@@ -31,6 +31,7 @@ async function Dropdowns() {
<DropdownMenuTrigger asChild className="flex">
{user ? (
<button
+ title="User dropdown menu"
className="border border-foreground-lighter rounded-full w-[30px] h-[30px] bg-no-repeat bg-center bg-cover"
style={{ backgroundImage: `url('${user.user_metadata.avatar_url}')` }}
/>
diff --git a/apps/database-new/data/messages-query.ts b/apps/database-new/data/messages-query.ts
index d8273a0f479..8b8bd4ea34e 100644
--- a/apps/database-new/data/messages-query.ts
+++ b/apps/database-new/data/messages-query.ts
@@ -1,28 +1,28 @@
-import { useQuery } from '@tanstack/react-query'
+// import { useQuery } from '@tanstack/react-query'
-import { ReadThreadAPIResult } from '@/lib/types'
+// import { ReadThreadAPIResult } from '@/lib/types'
-export type MessagesVariables = {
- threadId: string
- runId: string
- enabled?: boolean
-}
+// export type MessagesVariables = {
+// threadId: string
+// runId: string
+// enabled?: boolean
+// }
-export const useMessagesQuery = ({ threadId, runId, enabled }: MessagesVariables) =>
- useQuery<ReadThreadAPIResult>({
- queryKey: [threadId, runId],
- enabled: enabled && !!(threadId && runId),
- queryFn: async () => {
- const response = await fetch(`/api/ai/sql/threads/${threadId}/read/${runId}`, {
- method: 'GET',
- })
- const result = await response.json()
- return result
- },
- refetchInterval: (options) => {
- const data = options.state.data
- if (data && data.status === 'completed') {
- return Infinity
- } else return 5000
- },
- })
+// export const useMessagesQuery = ({ threadId, runId, enabled }: MessagesVariables) =>
+// useQuery<ReadThreadAPIResult>({
+// queryKey: [threadId, runId],
+// enabled: enabled && !!(threadId && runId),
+// queryFn: async () => {
+// const response = await fetch(`/api/ai/sql/threads/${threadId}/read/${runId}`, {
+// method: 'GET',
+// })
+// const result = await response.json()
+// return result
+// },
+// refetchInterval: (options) => {
+// const data = options.state.data
+// if (data && data.status === 'completed') {
+// return Infinity
+// } else return 5000
+// },
+// })
diff --git a/apps/database-new/lib/state.ts b/apps/database-new/lib/state.ts
index 806341175e1..71d1fc823e8 100644
--- a/apps/database-new/lib/state.ts
+++ b/apps/database-new/lib/state.ts
@@ -15,6 +15,11 @@ export const appState = proxy({
setLoginDialogOpen: (value: boolean) => {
appState.loginDialogOpen = value
},
+
+ runsLoading: [] as string[],
+ setRunsLoading: (value: string[]) => {
+ appState.runsLoading = value
+ },
})
export const getAppStateSnapshot = () => snapshot(appState)
diff --git a/packages/config/ui.config.js b/packages/config/ui.config.js
index 121fc445aa7..4988063a72a 100644
--- a/packages/config/ui.config.js
+++ b/packages/config/ui.config.js
@@ -281,6 +281,7 @@ const uiConfig = {
'panel-slide-right-in': 'panelSlideRightIn 250ms cubic-bezier(0.87, 0, 0.13, 1)',
'line-loading': 'lineLoading 1.8s infinite',
+ 'line-loading-slower': 'lineLoading 2.3s infinite',
// tailwind class for this is `animate-dropdownFadeIn`
dropdownFadeIn: 'dropdownFadeIn 0.1s ease-out',
diff --git a/packages/ui/src/components/Button/Button.tsx b/packages/ui/src/components/Button/Button.tsx
index e03cffa6b21..d6ce73c0372 100644
--- a/packages/ui/src/components/Button/Button.tsx
+++ b/packages/ui/src/components/Button/Button.tsx
@@ -2,11 +2,11 @@
import { Slot } from '@radix-ui/react-slot'
import { VariantProps, cva } from 'class-variance-authority'
-import React from 'react'
import { IconContext } from '@ui/components/Icon/IconContext'
import { IconLoader } from '@ui/components/Icon/icons/IconLoader'
import { sizes } from '@ui/lib/commonCva'
import { cn } from '@ui/lib/utils'
+import { cloneElement, forwardRef, isValidElement } from 'react'
export type ButtonVariantProps = VariantProps<typeof buttonVariants>
const buttonVariants = cva(
@@ -152,7 +152,7 @@ export interface ButtonProps
rounded?: boolean
}
-const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+const Button = forwardRef<HTMLButtonElement, ButtonProps>(
(
{
asChild = false,
@@ -186,8 +186,8 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
className={cn(buttonVariants({ type, size, disabled, block, rounded }), className)}
>
{asChild ? (
- React.isValidElement(children) ? (
- React.cloneElement(
+ isValidElement(children) ? (
+ cloneElement(
children,
undefined,
showIcon &&
diff --git a/packages/ui/src/components/LoadingLine/LoadingLine.tsx b/packages/ui/src/components/LoadingLine/LoadingLine.tsx
index d63961a3eea..a5cf2f2e154 100644
--- a/packages/ui/src/components/LoadingLine/LoadingLine.tsx
+++ b/packages/ui/src/components/LoadingLine/LoadingLine.tsx
@@ -9,7 +9,7 @@ export const LoadingLine = ({ loading }: { loading: boolean }) => {
'absolute w-[80px] h-px ml-auto mr-auto left-0 right-0 text-center block top-0',
'transition-all',
'line-loading-bg-light dark:line-loading-bg',
- loading && 'animate-line-loading opacity-100',
+ loading && 'animate-line-loading-slower opacity-100',
loading ? 'opacity-100' : 'opacity-0'
)}
></span>
diff --git a/packages/ui/src/patterns/AssistantChatForm.tsx b/packages/ui/src/patterns/AssistantChatForm.tsx
index 3543cb9ea70..ccbb469a67c 100644
--- a/packages/ui/src/patterns/AssistantChatForm.tsx
+++ b/packages/ui/src/patterns/AssistantChatForm.tsx
@@ -10,6 +10,7 @@ export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
value?: string
onValueChange: (value: ChangeEvent<HTMLTextAreaElement>) => void
message?: string
+ children?: React.ReactNode
}
const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
@@ -42,32 +43,6 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
}
}
- const TextAreaElement = () => {
- const { pending } = useFormStatus()
-
- return (
- <TextArea
- name="value"
- ref={textAreaRef}
- autoFocus
- rows={1}
- disabled={disabled || pending}
- contentEditable
- aria-expanded={false}
- aria-required={true}
- required
- className={
- 'transition-all text-sm pl-12 pr-10 rounded-[18px] resize-none box-border leading-6'
- }
- placeholder={props.placeholder}
- spellCheck={false}
- value={value}
- onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onValueChange(event)}
- onKeyDown={handleKeyDown}
- />
- )
- }
-
const SubmitButton = () => {
const { pending } = useFormStatus()
@@ -78,8 +53,10 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
) : null}
<button
+ title="Send AI prompt"
ref={submitRef}
type="submit"
+ disabled={pending}
className={cn(
'transition-all',
'flex items-center justify-center w-7 h-7 border border-control rounded-full mr-0.5 p-1.5 background-alternative',
@@ -109,7 +86,24 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
return (
<form ref={ref} className="relative" {...props}>
<div className={cn('absolute', 'top-2 left-2', 'ml-1 w-6 h-6 rounded-full bg-dbnew')}></div>
- <TextAreaElement />
+ <TextArea
+ name="value"
+ ref={textAreaRef}
+ autoFocus
+ rows={1}
+ disabled={disabled || submitRef.current?.disabled}
+ contentEditable
+ required
+ className={
+ 'transition-all text-sm pl-12 pr-10 rounded-[18px] resize-none box-border leading-6'
+ }
+ placeholder={props.placeholder}
+ spellCheck={false}
+ value={value}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onValueChange(event)}
+ onKeyDown={handleKeyDown}
+ />
+ {props.children}
<SubmitButton />
<p aria-live="polite" className="sr-only" role="status">
{message}