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

wip: fix thread-list load #373

Merged
merged 3 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
7 changes: 4 additions & 3 deletions apps/masterbots.ai/app/c/[category]/[chatbot]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { authOptions } from "@/auth";
import { ChatChatbot } from "@/components/routes/chat/chat-chatbot";
import ThreadPanel from "@/components/routes/thread/thread-panel";
import { botNames } from "@/lib/constants/bots-names";
import { PAGE_SM_SIZE } from "@/lib/constants/hasura";
import { PAGE_SIZE } from "@/lib/constants/hasura";
import { generateMetadataFromSEO } from "@/lib/metadata";
import { getChatbot, getThreads } from "@/services/hasura";
import { isTokenExpired } from "mb-lib";
Expand Down Expand Up @@ -43,8 +43,9 @@ export default async function BotThreadsPage({
throw new Error("User ID is missing.");
}

const threads = await getThreads({ chatbotName, jwt: jwt as string, userId, limit: PAGE_SM_SIZE });

const threads = await getThreads({ chatbotName, jwt: jwt as string, userId, limit: PAGE_SIZE });
console.log('threads::[chatbots] page --> ', threads.length)
console.log('threads::[chatbots] page::chatbotName --> ', chatbotName)
return (
<>
<ThreadPanel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ const ChatbotComponent: React.FC<ChatbotComponentProps> = React.memo(
)}
onClick={handleChatbotClick}
data-route={routeType}
prefetch
>
<Image
src={chatbot.avatar || '/path/to/default/avatar.png'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { cleanPrompt } from '@/lib/helpers/ai-helpers'
import { cn } from '@/lib/utils'
import type { Message } from 'ai'
import type { Chatbot } from 'mb-genql'
import type ExtraProps from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export function ClickableText({
key={`clickable-${
// biome-ignore lint/suspicious/noArrayIndexKey: <explanation>
index
}`}
}`}
className={cn(
'cursor-pointer hover:underline',
isListItem ? 'text-blue-500' : 'text-link'
Expand All @@ -153,8 +153,8 @@ export function ClickableText({
typeof item === 'string'
? item
: extractTextFromReactNodeNormal(
(item.props as { children: React.ReactNode }).children
)
(item.props as { children: React.ReactNode }).children
)
)
.join(' ')
return transformLink(content, parentContext)
Expand All @@ -174,7 +174,7 @@ export function ClickableText({
key={`clickable-${
// biome-ignore lint/suspicious/noArrayIndexKey: <explanation>
index
}`}
}`}
>
{renderClickableContent(clickableText, restText)}
</React.Fragment>
Expand Down
30 changes: 28 additions & 2 deletions apps/masterbots.ai/components/routes/thread/user-thread-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export default function UserThreadPanel({
}
}, [continuousThreadId, session])

const threads = state.threads.length ? state.threads : initialThreads
const threads = state.threads.length > initialThreads.length ? state.threads : initialThreads

// biome-ignore lint/correctness/useExhaustiveDependencies: This effect should run only when the active category or chatbot changes
useEffect(() => {
Expand Down Expand Up @@ -243,11 +243,37 @@ export default function UserThreadPanel({

return (
<>
{(page !== 'profile' || (page !== 'profile' && !isContinuousThread)) && (
{(threads.length !== 0 && (page !== 'profile' || (page !== 'profile' && !isContinuousThread))) && (
<div className="flex justify-between px-4 py-5 md:px-10 lg:max-w-full">
<ChatSearchInput setThreads={setState} onSearch={setSearchTerm} />
</div>
)}
{loading && (
<div className="flex justify-between px-4 py-5 md:px-10 lg:max-w-full">
<div className="relative w-full max-w-[900px] mx-auto flex items-center justify-center pt-5">
<div className="relative w-full">
<div className="absolute inset-0 transition-opacity duration-300 rounded-full opacity-0 group-focus-within:opacity-100">
<div className="absolute inset-0 rounded-full bg-gradient-to-r dark:from-[#83E56A]/5 dark:to-[#83E56A]/5 from-[#BE17E8]/5 to-[#BE17E8]/5 blur-lg animate-pulse" />
</div>

<div
className={cn(
'group relative w-full flex items-center',
'rounded-full',
'dark:bg-[#18181B]/90',
'border dark:border-[#83E56A]/10 border-[#BE17E8]/10',
'focus-within:border-[#BE17E8] dark:focus-within:border-[#83E56A]',
'focus-within:ring-1 focus-within:ring-[#BE17E8] dark:focus-within:ring-[#83E56A]',
'transition-all duration-200'
)}
>
<div className="absolute w-5 h-5 left-4 text-zinc-400 group-focus-within:text-[#BE17E8] dark:group-focus-within:text-[#83E56A] animate-pulse bg-gray-300 rounded-full" />
<div className="w-full px-12 py-6 bg-transparent placeholder:text-zinc-400 text-base dark:text-zinc-100 animate-pulse bg-gray-300 rounded-full" />
</div>
</div>
</div>
</div>
)}
<ul className={cn(
'flex flex-col size-full gap-3 pb-5 px-4 lg:px-10',
{
Expand Down
67 changes: 23 additions & 44 deletions apps/masterbots.ai/lib/hooks/use-mb-chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
createdAt: m.createdAt,
}))
: []
const systemPrompts: AiMessage[] = userPreferencesPrompts
.concat(chatbotSystemPrompts)
/**
* @description
* Concatenate all message to pass it to chat component.
Expand All @@ -112,9 +114,7 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
* 2. Chatbot System Prompts (IQ, Expertise).
* 3. Conversation between user and assistant.
* */
const initialMessages: AiMessage[] = userPreferencesPrompts
.concat(chatbotSystemPrompts)
.concat(userAndAssistantMessages)
const initialMessages: AiMessage[] = systemPrompts.concat(userAndAssistantMessages)

const threadId = activeThread?.threadId || randomThreadId.current
const chatbot = activeThread?.chatbot || activeChatbot
Expand Down Expand Up @@ -325,21 +325,6 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
threadId,
jwt: session?.user?.hasuraJwt,
})
} else {
const newAllMessages = uniqBy(
allMessages?.concat(
(newThread?.messages || []).map((m) => ({
id: m.messageId,
role: m.role as AiMessage['role'],
content: m.content,
createdAt: m.createdAt || new Date().toISOString(),
})),
),
'content',
)
// .filter((m) => m.role !== 'system')
// console.log('newAllMessages ---> ', newAllMessages)
setMessages(newAllMessages)
}

if (thread) {
Expand Down Expand Up @@ -411,7 +396,7 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
userId: session?.user.id,
}

const thread = await updateActiveThread(!activeThread || isNewChat ? optimisticThread : undefined)
const thread = await updateActiveThread(isNewChat ? optimisticThread : (activeThread || undefined))

if (!isOpenPopup) {
setIsOpenPopup(true)
Expand Down Expand Up @@ -513,33 +498,25 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
const chatbotMetadata = await getMetadataLabels()
const isUpdatedThreadNewChat = Boolean(!thread || (thread && thread.messages.length <= 1))

if (isUpdatedThreadNewChat) {
const newChatMessages = uniqBy(
[
{
id: 'examples-' + nanoid(10),
role: 'system' as 'data' | 'system' | 'user' | 'assistant',
content: examplesPrompt(chatbotMetadata),
},
...initialMessages,
...allMessages,
],
'content',
)
setMessages(newChatMessages)

if (appConfig.features.devMode) {
console.log('newChatMessages --> ', newChatMessages)
console.log('Chatbot metadata --> ', chatbotMetadata)
}
}
const newChatMessages = uniqBy(
[
{
id: 'examples-' + nanoid(10),
role: 'system' as 'data' | 'system' | 'user' | 'assistant',
content: examplesPrompt(chatbotMetadata),
},
...initialMessages,
],
'content',
)
setMessages(newChatMessages)

// What remedies are good for stress relieve?
if (appConfig.features.devMode && !isUpdatedThreadNewChat) {
console.log('allMessages --> ', allMessages)
if (appConfig.features.devMode) {
console.log('newChatMessages --> ', newChatMessages)
console.log('Chatbot metadata --> ', chatbotMetadata)
}


if (isUpdatedThreadNewChat && chatbot) {
await createThread({
threadId: threadId as string,
Expand All @@ -553,9 +530,11 @@ export function MBChatProvider({ children }: { children: React.ReactNode }) {
const appendResponse = await append(
{
...userMessage,
content: isNewChat
// ! This condition is not working as expected 🤔 it is now overkill to have the following question
// ! due the UI force us to switch the paradigm on how the new messages display into the conversation (going upwards instead down as it should)
content: isUpdatedThreadNewChat
? userContentRef.current
: followingQuestionsPrompt(userContentRef.current, messages),
: followingQuestionsPrompt(userContentRef.current, allMessages.filter(msg => msg.role === 'user')),
},
// ? Provide chat attachments here...
// {
Expand Down
13 changes: 11 additions & 2 deletions apps/masterbots.ai/lib/hooks/use-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getCategories, getUserBySlug } from '@/services/hasura'
import type { Category, Chatbot } from 'mb-genql'
import { toSlug } from 'mb-lib'
import { useSession } from 'next-auth/react'
import { useParams, usePathname } from 'next/navigation'
import { useParams, usePathname, useRouter } from 'next/navigation'
import * as React from 'react'
import { useAsync } from 'react-use'

Expand Down Expand Up @@ -65,6 +65,7 @@ export function SidebarProvider({ children }: SidebarProviderProps) {
const { data: session } = useSession()
const { slug } = useParams()
const pathname = usePathname()
const router = useRouter()
const prevPath = React.useRef<string | null>(null)

const {
Expand Down Expand Up @@ -271,7 +272,15 @@ export function SidebarProvider({ children }: SidebarProviderProps) {
isBrowse,
}: NavigationParams): void => {
const url = buildNavigationUrl({ page, slug, categoryName, chatbotName, isBrowse })
window.history.pushState({}, '', url)

if (url.startsWith('/c')) {
router.push(url, { scroll: false })
} else {
window.history.pushState({
category: categoryName,
chatbot: chatbotName,
}, '', url)
}
}

if (isLoading) {
Expand Down
3 changes: 2 additions & 1 deletion apps/masterbots.ai/lib/threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export function getAllUserMessagesAsStringArray(allMessages: Message[] | AI.Mess
const cleanMessages = userMessages.map((m) =>
extractBetweenMarkers(
m.content,
'OK, so following the same pattern, how would you answer the question:',
// 'OK, so following the same pattern, how would you answer the question:',
'First, think about the following questions and requests: [',
),
)
return cleanMessages.join(', ')
Expand Down
Binary file modified bun.lockb
Binary file not shown.