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

fix: isNewChat regression #382

Merged
merged 8 commits into from
Feb 20, 2025
Merged

fix: isNewChat regression #382

merged 8 commits into from
Feb 20, 2025

Conversation

AndlerRL
Copy link
Member

@AndlerRL AndlerRL commented Feb 20, 2025

Summary by Sourcery

Addresses an issue where new chats were not starting correctly and enhances error handling and chat state management. The changes ensure that new threads are properly created and that users receive informative error messages when message sending fails.

Bug Fixes:

  • Fixes a regression where new chats were not being properly initiated, ensuring that new threads are created as expected when starting a conversation with a chatbot.

Enhancements:

  • Improves the user experience by resetting the chat state when the chat popup is closed.
  • Adds a user-friendly error message when sending a message to the Masterbot fails.

Summary by CodeRabbit

  • New Features

    • Updated the chat interface message for thread continuity, now displaying "Continue this thread here" to guide users.
  • Bug Fixes

    • Enhanced error notifications to provide clearer feedback when sending a message fails.
  • Chores

    • Removed automatic scrolling behavior when new messages are loaded in the chat thread, which may affect user experience during active chats.
    • Updated parameter name in the Chat component for clarity.

@AndlerRL AndlerRL self-assigned this Feb 20, 2025
Copy link

sourcery-ai bot commented Feb 20, 2025

Reviewer's Guide by Sourcery

This pull request fixes a regression that prevented new chats from being properly initiated. It also updates the text for creating a new thread and adds an error notification for when sending messages fails. The primary change involves adjusting the conditions under which a new chat thread is created within the use-mb-chat hook.

Sequence diagram for creating a new chat thread

sequenceDiagram
    participant User
    participant MBChatProvider
    participant getMetadataLabels
    participant createThread

    User->>MBChatProvider: Sends a message to the chatbot
    activate MBChatProvider
    MBChatProvider->>getMetadataLabels: Fetches chatbot metadata
    activate getMetadataLabels
    getMetadataLabels-->>MBChatProvider: Returns chatbot metadata
    deactivate getMetadataLabels
    alt isNewChat && chatbot
        MBChatProvider->>createThread: Creates a new thread
        activate createThread
        createThread-->>MBChatProvider: Returns the new thread ID
        deactivate createThread
    end
    MBChatProvider-->>User: Displays the chatbot's response
    deactivate MBChatProvider
Loading

Updated class diagram for MBChatProvider

classDiagram
    class MBChatProvider {
        -messagesFromDB: Message[]
        -isNewChat: boolean
        +sendMessage(message: string): Promise<void>
        +createThread(threadId: string, chatbotId: string, title: string): Promise<void>
    }

    note for MBChatProvider "The isInitLoaded and loadingState properties were removed."
Loading

File-Level Changes

Change Details Files
Fixed a regression where new chats were not being properly initiated.
  • Removed loadingState from the useSetState hook's state object.
  • Modified the useEffect hook that resets the chat state when the popup is closed to correctly handle the isNewChat state.
  • Updated the condition for creating a new thread to only check for isNewChat instead of also checking for the length of messages in the active thread.
  • Added a customSonner notification to display an error message when appending a new message fails.
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx
Updated the text for creating a new thread.
  • Modified the return value of the thread title to 'Continue this thread here' when isContinuousThread and allMessages are true.
apps/masterbots.ai/components/routes/chat/chat.tsx

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

vercel bot commented Feb 20, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
masterbots ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 20, 2025 6:33am

Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Walkthrough

This pull request introduces modifications to the chat functionality by refining messaging logic and streamlining state management. In the Chat component, the import for useMBScroll is updated, and the message returned by chatSearchMessage when isContinuousThread is true is changed to "Continue this thread here." In the MBChatProvider hook, the state structure is simplified by removing loadingState and isInitLoaded, and error handling in the appendNewMessage function is enhanced. Additionally, a clarifying comment is added to the useEffect hook that resets the chat.

Changes

File Change Summary
apps/masterbots.ai/components/.../chat.tsx Added new import for useMBScroll and removed the previous one. Updated the chatSearchMessage function to return "Continue this thread here" when isContinuousThread is true, modifying the user-facing messaging logic.
apps/masterbots.ai/lib/hooks/.../use-mb-chat.tsx Removed loadingState and isInitLoaded from the state. Updated the condition in appendNewMessage to only check isNewChat. Enhanced error messaging in the catch block and added a clarifying comment in a relevant useEffect.
apps/masterbots.ai/components/.../thread-popup.tsx Commented out code in useEffect that handled automatic scrolling to the bottom of the chat thread when new messages were loading, affecting the automatic scrolling behavior during active chats.

Possibly related PRs

  • Refactor: useScroll hook #376: Involves modifications to the Chat component in chat.tsx, specifically related to scrolling behavior with the useMBScroll hook.
  • Impr: improve current features v2 #274: Focuses on modifying the chatSearchMessage function's return value in the Chat component, while also altering the sendMessageFromResponse function in the same file.
  • Feat: user messages ai refactor #266: Addresses modifications in the Chat component's messaging logic, linking to enhancements made with the improveMessage function.

Suggested labels

bug, enhancement

Poem

Oh, I hop with gleeful code today,
Threads continue in a brand new way.
My whiskers twitch at every change,
In chat and state, nothing feels strange.
Happy hops and a bug-free display! 🥕💻

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/masterbots.ai/lib/hooks/use-mb-chat.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/apps/masterbots.ai/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

apps/masterbots.ai/components/routes/thread/thread-popup.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/apps/masterbots.ai/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @AndlerRL - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a comment explaining why activeThread?.messages.length was removed from the conditional.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/masterbots.ai/components/routes/chat/chat.tsx (1)

123-124: Consider keeping the thread title in the message.

The previous message provided more context by showing the thread title. The new static message "Continue this thread here" is less informative.

Consider reverting to the previous message or combining both:

-// return `Create new thread from "${threadTitle}" by making a new question.`
-return 'Continue this thread here'
+return `Continue thread "${threadTitle}" here`
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee02241 and 242c16c.

📒 Files selected for processing (2)
  • apps/masterbots.ai/components/routes/chat/chat.tsx (2 hunks)
  • apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (4 hunks)
🔇 Additional comments (4)
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (4)

67-77: LGTM! State cleanup.

The removal of isInitLoaded from state is a good cleanup as it's not used elsewhere in the code.


277-278: LGTM! Clear comment.

The added comment clearly explains the purpose of the useEffect hook.


551-551: LGTM! Improved error message.

The error message is now more specific about the failure being related to sending a message to the Masterbot.


486-494:

✅ Verification successful

Verify thread creation logic.

The condition for creating a new thread has been simplified to only check isNewChat. Please verify that this doesn't miss any edge cases that were previously caught by checking activeThread?.messages.length.

Run this script to check thread creation patterns:


🏁 Script executed:

#!/bin/bash
# Description: Search for thread creation patterns to verify the change is safe

# Search for thread creation conditions
rg -A 5 "createThread\(" 

# Search for isNewChat usage
rg -A 5 "isNewChat"

Length of output: 12697


Thread Creation Logic Verified: No Edge Cases Missed

After reviewing the code and verifying the output of the search scripts, it appears that the isNewChat state is correctly derived from the absence of messages in activeThread (i.e., using Boolean(!activeThread?.messages.length)). This means that the previous edge case—where an empty message list was explicitly checked—is now implicitly handled by isNewChat. The thread creation in apps/masterbots.ai/lib/hooks/use-mb-chat.tsx now safely relies on this state.

No further modifications seem necessary. Please ensure that integration tests continue to cover these scenarios for future changes.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/masterbots.ai/components/routes/thread/thread-popup.tsx (1)

45-57: Verify the impact of removing auto-scroll functionality.

The commented-out useEffect hook was responsible for automatically scrolling to the bottom when new messages load. While manual scrolling is still available through the Chat component, verify that this change doesn't negatively impact the user experience during active chats.

Consider keeping the auto-scroll functionality but with these improvements:

-  // Uses smoothScrollToBottom from custom hook useMBScroll
-  // biome-ignore lint/correctness/useExhaustiveDependencies: smoothScrollToBottom might be necessary however, it has his own memoization (useCallback). That should be enough, else, can be added as a dependency
-   useEffect(() => {
-   let timeout: NodeJS.Timeout
-   if (isLoading && isOpenPopup) {
-     timeout = setTimeout(() => {
-       smoothScrollToBottom()
-     }, 150)
-   }
-   return () => {
-     clearTimeout(timeout)
-   }
- }, [isLoading, isOpenPopup])
+  useEffect(() => {
+    if (isLoading && isOpenPopup && !isNearBottom) {
+      const timeout = setTimeout(smoothScrollToBottom, 150)
+      return () => clearTimeout(timeout)
+    }
+  }, [isLoading, isOpenPopup, isNearBottom, smoothScrollToBottom])
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 242c16c and ab85a11.

📒 Files selected for processing (2)
  • apps/masterbots.ai/components/routes/thread/thread-popup.tsx (1 hunks)
  • apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (5 hunks)
🔇 Additional comments (4)
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (4)

67-78: LGTM! State management improvements.

The state structure has been simplified by:

  • Removing unnecessary isInitLoaded state
  • Deriving isNewChat directly from activeThread.messages.length
  • Using a more explicit boolean conversion

552-552: LGTM! Improved error message clarity.

The error message has been made more specific and user-friendly, clearly indicating that the message failed to send to the Masterbot.


278-286: Verify chat reset behavior.

The useEffect hook now includes a clarifying comment and resets the chat state when there's no active thread and the popup is closed. Verify that this doesn't cause any unintended state resets during normal chat interactions.


487-495:

✅ Verification successful

Verify the simplified thread creation condition.

The thread creation condition has been simplified to only check isNewChat. Verify that this doesn't cause any edge cases where threads might be created unnecessarily or not created when needed.


🏁 Script executed:

#!/bin/bash
# Search for other thread creation conditions in the codebase
ast-grep --pattern 'createThread({
  $$$
})'

Length of output: 1314


Thread creation condition verified

The simplified condition in use-mb-chat.tsx—checking only isNewChat && chatbot—appears consistent with the thread creation logic used elsewhere (e.g., in new-chat.tsx). The conditional construction still accounts for continuous threads through the isContinuousThread ? activeThread?.threadId : undefined handling and the public check via activeChatbot?.name !== 'BlankBot'. Based on the codebase search, no edge cases were identified that would result in unnecessary thread creation or omission, so the change seems both intentional and maintainable.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (3)

541-541: Enhance error message clarity.

The error message has been improved to be more specific about the failure point (Masterbot). However, consider adding error details for debugging in development mode.

-      customSonner({ type: 'error', text: 'Failed to send the message to the Masterbot. Please try again.' })
+      customSonner({ 
+        type: 'error', 
+        text: 'Failed to send the message to the Masterbot. Please try again.',
+        ...(appConfig.features.devMode && { description: error.message })
+      })

488-499: Potential memory optimization for chat messages.

The uniqBy operation on system prompts could be memoized since these messages don't change frequently.

+  const memoizedSystemPrompts = useMemo(() => uniqBy(
+    [
+      ...systemPrompts,
+      {
+        id: 'examples-' + nanoid(10),
+        role: 'system' as 'data' | 'system' | 'user' | 'assistant',
+        content: examplesPrompt(chatbotMetadata),
+      },
+    ],
+    'content',
+  ), [systemPrompts, chatbotMetadata])
+
-      const chatMessagesToAppend = uniqBy(
-        [
-          ...systemPrompts,
-          {
-            id: 'examples-' + nanoid(10),
-            role: 'system' as 'data' | 'system' | 'user' | 'assistant',
-            content: examplesPrompt(chatbotMetadata),
-          },
-        ],
-        'content',
-      )
+      const chatMessagesToAppend = memoizedSystemPrompts

519-533: Consider adding retry mechanism for append operations.

The append operation could benefit from a retry mechanism to handle transient failures, especially since it's a critical operation for chat functionality.

+      const MAX_RETRIES = 3;
+      const RETRY_DELAY = 1000;
+      let retries = 0;
+      let appendResponse = null;
+
+      while (retries < MAX_RETRIES) {
+        try {
           const appendResponse = await append(
             {
               ...userMessage,
               content: isNewChat
                 ? userContentRef.current
                 : followingQuestionsPrompt(
                   userContentRef.current,
                   previousAiUserMessages.concat(userMessages),
                 ),
             },
           )
+          break;
+        } catch (error) {
+          retries++;
+          if (retries === MAX_RETRIES) throw error;
+          await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
+        }
+      }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab85a11 and 8bc5eb2.

📒 Files selected for processing (2)
  • apps/masterbots.ai/components/routes/thread/thread-popup.tsx (2 hunks)
  • apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/masterbots.ai/components/routes/thread/thread-popup.tsx
🔇 Additional comments (3)
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (3)

67-78: Improved state initialization logic.

The initialization of isNewChat now correctly derives from the thread's message length, making it more reliable and consistent with the actual state of the conversation.


267-275: Clear documentation of chat reset behavior.

The added comment clearly explains the purpose of resetting the chat when the popup is closed, improving code maintainability.


476-484:

❓ Verification inconclusive

Verify thread creation logic.

The condition for creating a new thread has been simplified to only check isNewChat. However, we should verify that this doesn't create unnecessary threads.


🏁 Script executed:

#!/bin/bash
# Search for other thread creation conditions in the codebase
rg "createThread\(" -A 5

Length of output: 1548


Thread creation condition appears consistent but please double-check parameter differences.

After searching for all calls to createThread, we confirmed that in the hook (apps/masterbots.ai/lib/hooks/use-mb-chat.tsx, lines 476–484) the thread is only created when both isNewChat and a valid chatbot are present. This simplified condition is in line with the similar call in apps/masterbots.ai/components/routes/chat/new-chat.tsx—except that the latter also provides a userId. No evidence was found that this simplified logic is causing duplicate or unnecessary thread creations. Please verify that omitting userId in this hook is intentional based on your requirements.

@AndlerRL AndlerRL merged commit 071ee3f into develop Feb 20, 2025
2 checks passed
@AndlerRL AndlerRL deleted the hotfixes-post-merge branch February 20, 2025 11:05
AndlerRL added a commit that referenced this pull request Feb 21, 2025
… regression + followingQuestionPrompt (#383)

* [masterbots.ai] fix: isNewChat regression (#382)

* impr: continue thread placeholder

* fix: isNewChat regression

* fix: isNewChat state

* impr: error toaster at appendNewMessage

* style: console.log cleanup

* impr: initIsNewChat guard

* impr: thread-popup scrolldown

* impr: scrollToBottomPopup + onFinish cb

* chore: enable onFinished and appendingNewMessage logs + env var openai config

* fix: typo

* fix: typo

* fix: createThread condition

* impr: isnewChat guard

* impr: isnewChat guard

* fix: ts typo

* fix: loaders + getAllUserMessagesAsStringArray cleanup

* impr: chat panel a11y
@coderabbitai coderabbitai bot mentioned this pull request Feb 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant