Skip to content

Code Cleanup: Remove Unused Imports, Update UI/Auth, Memoize Markdown#428

Merged
AndlerRL merged 5 commits intomainfrom
develop
Apr 1, 2025
Merged

Code Cleanup: Remove Unused Imports, Update UI/Auth, Memoize Markdown#428
AndlerRL merged 5 commits intomainfrom
develop

Conversation

@AndlerRL
Copy link
Member

@AndlerRL AndlerRL commented Apr 1, 2025

@coderabbitai provide a description using changelog format.

Summary by Sourcery

Refactor and improve various components and utilities across the masterbots.ai application, focusing on code organization, performance, and user experience

Enhancements:

  • Introduced a centralized markdown components utility for consistent rendering across different components
  • Added a device detection hook to support responsive design
  • Improved code block and markdown rendering with more flexible processing
  • Simplified routing and navigation logic in various components

Tests:

  • Ensured consistent markdown rendering across different components
  • Improved error handling and edge cases in utility functions

Chores:

  • Updated Next.js and React dependencies to latest versions
  • Cleaned up unused imports and simplified component logic
  • Improved type safety and reduced code duplication

Summary by CodeRabbit

  • New Features

    • Added a back navigation element on thread pages to facilitate easier user movement.
    • Updated authentication flows to redirect users to a new landing path after sign in/up.
  • Refactor

    • Consolidated Markdown rendering logic across messaging components for streamlined processing.
    • Simplified navigation parameter handling and refined message sorting for clearer conversation flow.
  • Style

    • Adjusted responsive layouts and refined button texts for a cleaner, more intuitive interface.
    • Enhanced code block support with expanded programming language options.
  • Chores

    • Upgraded key dependencies for improved stability and performance.

Bran18 and others added 5 commits March 26, 2025 18:06
* update

* fix: update

* update

* update

* update

* update

* fix: opening threads

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: update

* fix: added back to profile page

* fix: added sticky and color
…ock & clipboard hook (#425)

* fix: codeblock ctas

* fix: ts build
…426)

* fix: css handleCLick condition

* fix: get latest search params, continuous thread

* fix(impr): all messages sorting

* perf(impr): sign in & up redirection tweak

* perf(impr): mobile chat css
@AndlerRL AndlerRL self-assigned this Apr 1, 2025
@sourcery-ai
Copy link

sourcery-ai bot commented Apr 1, 2025

Reviewer's Guide by Sourcery

This pull request includes several enhancements and refactorings across the application. It standardizes Markdown rendering using a memoized component, improves chat thread handling and URL parameter management, enhances UI/UX with visual tweaks, and updates dependencies. It also fixes a bug where the clipboard API was not available and removes an unused import.

Updated class diagram for useDevice hook

classDiagram
    class DeviceInfo {
        +isMobile: boolean
        +isTablet: boolean
        +isDesktop: boolean
    }

    class useDevice {
        +(): DeviceInfo
    }

    useDevice -- DeviceInfo: returns
Loading

File-Level Changes

Change Details Files
Refactors Markdown rendering components to use a memoized component for consistent styling and functionality across the application.
  • Removes duplicated Markdown rendering logic from ChatMessage, ReasoningChatMessage, ThreadBlogMarkDown, BrowseChatMessage, and ShortMessage components.
  • Introduces memoizedMarkdownComponents in lib/memoized-markdown-components.tsx to provide a single source of truth for Markdown component configurations.
  • Updates components to import and use memoizedMarkdownComponents for rendering Markdown content.
  • Adds a conditional shouldPreProcessChildren prop to memoizedMarkdownComponents to allow enabling or disabling of child preprocessing.
  • Updates the CodeBlock component to prevent event propagation on copy and download actions.
  • Updates the CodeBlock component to generate a random string of length 6 for the suggested file name.
  • Updates the CodeBlock component to use the txt extension as the default file extension.
apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx
apps/masterbots.ai/components/routes/chat/chat-message.tsx
apps/masterbots.ai/components/shared/thread-blog-markdown.tsx
apps/masterbots.ai/components/routes/browse/browse-chat-message.tsx
apps/masterbots.ai/components/shared/short-message.tsx
apps/masterbots.ai/lib/memoized-markdown-components.tsx
apps/masterbots.ai/components/ui/codeblock.tsx
Improves chat thread handling and URL parameter management.
  • Updates the MBChatProvider to use the threadId directly instead of params.threadId.
  • Introduces getCurrentSearchParams to reliably check and retrieve URL search parameters, addressing issues with useSearchParams not updating correctly on page reload.
  • Modifies the logic for determining parentThreadId to use getCurrentSearchParams.
  • Removes unnecessary checks for params?.threadId when deleting threads.
  • Updates the sorting logic for messages in use-mb-chat.tsx to handle cases where createdAt timestamps are missing or identical, ensuring correct message order.
  • Removes the Stop text from the stop button in ChatPanel.
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx
apps/masterbots.ai/components/routes/chat/chat-panel.tsx
Enhances UI/UX with minor visual and functional improvements.
  • Updates the reasoning chat message to use a ChevronsDownUp icon instead of custom SVG.
  • Updates the loading indicator to use shorter messages on mobile devices.
  • Adds a back button to the browse thread blog and browse chat messages pages.
  • Updates the thread popup component to improve responsiveness on smaller screens.
  • Updates the feature toggle component to remove the label.
  • Updates the profile page sidebar to remove the link.
  • Updates the sidebar link component to support pro routes.
  • Updates the signin and signup forms to redirect to /c after successful authentication.
  • Updates the thread component to improve the arrow alignment.
  • Updates the shared accordion component to improve the arrow alignment.
apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx
apps/masterbots.ai/components/shared/loading-indicator.tsx
apps/masterbots.ai/app/u/[userSlug]/t/[category]/[domain]/[chatbot]/[threadSlug]/page.tsx
apps/masterbots.ai/components/routes/browse/browse-chat-messages.tsx
apps/masterbots.ai/components/routes/thread/thread-popup.tsx
apps/masterbots.ai/components/shared/feature-toggle.tsx
apps/masterbots.ai/components/layout/profile/profile-page-sidebar.tsx
apps/masterbots.ai/components/layout/sidebar/sidebar-link.tsx
apps/masterbots.ai/components/auth/signin-form.tsx
apps/masterbots.ai/components/auth/signup-form.tsx
apps/masterbots.ai/components/routes/thread/thread-component.tsx
apps/masterbots.ai/components/shared/shared-accordion.tsx
Updates dependencies.
  • Updates the nextjs dependency from 15.2.2 to 15.2.4.
  • Updates the react dependency from 19.0.0 to 19.1.0.
  • Updates the react-dom dependency from 19.0.0 to 19.1.0.
  • Updates the eslint-config-next dependency from 15.2.2 to 15.2.4.
apps/masterbots.ai/package.json
Fixes a bug where the clipboard API was not available.
  • Adds a check to see if the clipboard API is available before attempting to use it.
apps/masterbots.ai/lib/hooks/use-copy-to-clipboard.tsx
Removes unused import.
  • Removes unused import of Image and Link from app/b/[botSlug]/[threadSlug]/page.tsx.
apps/masterbots.ai/app/b/[botSlug]/[threadSlug]/page.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

@vercel
Copy link

vercel bot commented Apr 1, 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 Apr 1, 2025 2:10am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 1, 2025

Walkthrough

This pull request comprises multiple modifications across the codebase. Changes include the removal of unused imports, the addition of back-navigation elements and UI enhancements, updates to redirection behavior in authentication components, and consolidation of Markdown rendering logic via a new memoization function. There are also adjustments in styling for layout components, expanded support in the code block component, improvements in hook functionalities, and dependency updates in the package file.

Changes

File(s) Summary
apps/masterbots.ai/app/…/page.tsx (bot & user variants) Removed unused Image and Link imports in one page; in another, added a new back-navigation link with ChevronLeft icon and constructed profile URL.
apps/masterbots.ai/components/auth/signin-form.tsx
apps/masterbots.ai/components/auth/signup-form.tsx
Modified redirection after authentication from '/' to '/c'.
apps/masterbots.ai/components/layout/profile/profile-page-sidebar.tsx
apps/masterbots.ai/components/layout/sidebar/sidebar-link.tsx
apps/masterbots.ai/components/routes/thread/thread-component.tsx
apps/masterbots.ai/components/routes/thread/thread-popup.tsx
Commented out a navigation Link and introduced an isPro flag; updated styling (arrowClass, responsive paddings) for layout and sidebar components.
apps/masterbots.ai/components/routes/browse/browse-chat-message.tsx
apps/masterbots.ai/components/routes/chat/chat-message.tsx
apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx
apps/masterbots.ai/components/shared/short-message.tsx
apps/masterbots.ai/components/shared/thread-blog-markdown.tsx
apps/masterbots.ai/lib/memoized-markdown-components.tsx
Removed inline Markdown component definitions in favor of a centralized memoizedMarkdownComponents function; updated click handling and preprocessing logic.
apps/masterbots.ai/components/routes/browse/browse-chat-messages.tsx
apps/masterbots.ai/components/routes/chat/chat-panel.tsx
apps/masterbots.ai/components/shared/shared-accordion.tsx
Added new back-navigation UI elements, updated button text, and restructured accordion trigger for better alignment.
apps/masterbots.ai/components/ui/codeblock.tsx Expanded support for programming languages and file extensions; updated event handling in copy and download functions, and adjusted styling (z-10, pointer-events).
apps/masterbots.ai/lib/hooks/use-copy-to-clipboard.tsx
apps/masterbots.ai/lib/hooks/use-device.tsx
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx
apps/masterbots.ai/lib/utils.ts
Added console logging for clipboard issues; introduced a new useDevice hook for responsive device info; updated chat hook parameters (using threadSlug and adding getCurrentSearchParams); extended RouteType with a 'pro' value.
apps/masterbots.ai/package.json Upgraded dependency versions for Next.js, React, ReactDOM, @types/react, and eslint-config-next; removed the overrides section.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ThreadPage
    participant BackLink
    participant Router

    User->>ThreadPage: Views thread page
    User->>BackLink: Clicks "Back" link (with ChevronLeft)
    BackLink->>Router: Triggers navigation to profile URL (constructed from params)
    Router-->>User: Loads the profile page
Loading
sequenceDiagram
    participant User
    participant AuthForm
    participant Router

    User->>AuthForm: Submits login/sign-in details
    AuthForm->>Router: On success, calls router.push('/c')
    Router-->>User: Navigates to '/c'
Loading

Possibly related PRs

Suggested labels

enhancement

Poem

I'm a rabbit, quick on my feet,
Hopping through code, a rhythmic beat.
Imports slimming and paths refined,
Markdown magic now well-aligned.
With every change, I joyfully leap—
Happy bytes and carrots to keep!
🐇🌟

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/components/auth/signin-form.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/app/u/[userSlug]/t/[category]/[domain]/[chatbot]/[threadSlug]/page.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/layout/profile/profile-page-sidebar.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.

  • 20 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@AndlerRL
Copy link
Member Author

AndlerRL commented Apr 1, 2025

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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:

  • The removal of the preprocessChildren function and its usage in the MemoizedReactMarkdown components is a good simplification.
  • Consider adding a comment explaining why the sorting logic in MBChatProvider was changed.
  • The addition of memoizedMarkdownComponents is a great way to avoid re-rendering markdown components.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 2 issues found
  • 🟢 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.

@coderabbitai coderabbitai bot changed the title @coderabbitai Code Cleanup: Remove Unused Imports, Update UI/Auth, Memoize Markdown Apr 1, 2025
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: 2

🧹 Nitpick comments (14)
apps/masterbots.ai/lib/hooks/use-copy-to-clipboard.tsx (1)

15-17: Consider enhancing error handling beyond console logging.

The added console log is helpful for debugging, but this implementation still silently fails from the user's perspective. Consider enhancing this to provide user feedback when the clipboard API isn't available.

if (typeof window === 'undefined' || !navigator.clipboard?.writeText) {
  console.log('Clipboard API not available')
- return
+ return false
}

// Later in the function, when successful:
navigator.clipboard.writeText(value).then(() => {
  setIsCopied(true)
  // ...
})

// Update the return type to include success status
return { isCopied, copyToClipboard, success: boolean }
apps/masterbots.ai/components/layout/profile/profile-page-sidebar.tsx (1)

72-105: Consider removing commented code instead of keeping it

The Link component for the "Threads" section has been commented out, effectively disabling navigation to the user's profile. While commenting code can be useful during development, for production code it's better to remove unused code entirely rather than leave it commented out.

-							{/* <Link
-								href={urlBuilders.profilesUrl({
-									type: 'user',
-									usernameSlug: userSlug as string,
-								})}
-								onClick={handleToggleThreads}
-								className={cn(
-									'flex w-full items-center justify-between px-4 py-3',
-									'hover:bg-gray-200 dark:hover:bg-mirage transition-colors duration-200',
-									isThreadsOpen || openSidebar
-										? 'bg-gray-200 dark:bg-mirage'
-										: '',
-								)}
-								// biome-ignore lint/a11y/useSemanticElements: This is a button that redirects you to a page
-								role="button"
-								aria-expanded={isThreadsOpen}
-								aria-controls="threads-panel"
-								onKeyDown={(e) => {
-									if (e.key === 'Enter' || e.key === 'Space') {
-										handleToggleThreads()
-									}
-								}}
-							>
-								<div className="flex items-center space-x-2">
-									<MessagesSquare className="w-5 h-5" />
-									<span className="font-normal">Threads</span>
-								</div>
-								<IconCaretRight
-									className={cn(
-										'transition-transform duration-300 stroke-[#09090b] dark:stroke-[#FAFAFA]',
-										isThreadsOpen ? 'rotate-90' : 'rotate-0',
-									)}
-								/>
-							</Link> */}

Also, if this navigation functionality is no longer needed, you may want to review if the handleToggleThreads function and the isThreadsOpen state are still necessary.

apps/masterbots.ai/components/routes/browse/browse-chat-messages.tsx (1)

19-19: Verify unused Button import

The Button component is imported but doesn't appear to be used in the new code. Only buttonVariants is used (in the existing code at line 146).

-import { Button, buttonVariants } from '@/components/ui/button'
+import { buttonVariants } from '@/components/ui/button'
apps/masterbots.ai/components/routes/browse/browse-chat-message.tsx (1)

28-28: Improved code organization with memoized components

Centralizing markdown rendering components into a memoized function is a great architectural improvement. This change enhances maintainability, ensures consistent rendering across components, and potentially improves performance through memoization.

Consider adding a comment explaining the benefits of using the memoized components here, especially for future developers who might not be familiar with the pattern.

Also applies to: 54-54

apps/masterbots.ai/lib/hooks/use-device.tsx (1)

1-39: Well-implemented responsive design hook

The useDevice hook is a well-structured implementation for detecting device types based on screen width. It follows React best practices with proper state management and cleanup.

Consider adding debouncing to the resize event handler to improve performance when resize events fire rapidly:

import { useEffect, useState } from 'react'
+import { debounce } from 'lodash' // Assuming lodash is available based on package.json

export interface DeviceInfo {
	isMobile: boolean
	isTablet: boolean
	isDesktop: boolean
}

export function useDevice(): DeviceInfo {
	const [deviceInfo, setDeviceInfo] = useState<DeviceInfo>({
		isMobile: false,
		isTablet: false,
		isDesktop: true,
	})

	useEffect(() => {
		const updateDeviceInfo = () => {
			const width = window.innerWidth
			setDeviceInfo({
				isMobile: width < 768,
				isTablet: width >= 768 && width < 1024,
				isDesktop: width >= 1024,
			})
		}

+		const debouncedUpdateDeviceInfo = debounce(updateDeviceInfo, 100)
		
		//? Runs once on mount
		updateDeviceInfo()

		//? Add event listener
-		window.addEventListener('resize', updateDeviceInfo)
+		window.addEventListener('resize', debouncedUpdateDeviceInfo)

		//? Cleanup
		return () => {
-			window.removeEventListener('resize', updateDeviceInfo)
+			window.removeEventListener('resize', debouncedUpdateDeviceInfo)
+			debouncedUpdateDeviceInfo.cancel()
		}
	}, [])

	return deviceInfo
}
apps/masterbots.ai/lib/memoized-markdown-components.tsx (2)

1-52: Well-structured utility for consistent Markdown processing

The preprocessChildren function efficiently handles combining adjacent nodes with colons, which provides consistent rendering across the application.

Consider adding a more detailed explanation for the biome-ignore comment on line 29:

-			// biome-ignore lint/suspicious/noExplicitAny: <explanation>
+			// biome-ignore lint/suspicious/noExplicitAny: React.ReactElement requires generic typing

54-217: Excellent centralization of Markdown component rendering

The memoizedMarkdownComponents function effectively centralizes custom Markdown rendering logic, promoting consistent styling and behavior across the application.

Consider addressing the TypeScript @ts-ignore comments by properly typing the component props:

-		// @ts-ignore
-		p({ children }) {
+		p: ({ children, node, ...props }: { 
+			children: React.ReactNode; 
+			node?: any; 
+			[key: string]: any 
+		}) => {

Apply similar typing to other component functions to eliminate @ts-ignore comments.

For the code block key generation, consider a more robust approach:

-			const codeBlockKey = `code-${language || ''}-${String(children).substring(0, 20).replace(/\n$/, '').replace(/\s/g, '-')}`
+			const codeBlockKey = `code-${language || ''}-${hashString(String(children))}`

Where hashString could be a simple hash function:

function hashString(str: string): string {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32bit integer
  }
  return Math.abs(hash).toString(36);
}

This would provide more unique and consistent keys for code blocks, especially when similar content is present.

apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx (1)

96-96: Using content as key might cause issues with duplicate lines

While using line content as a key is generally better than using an index, it could cause issues if the same line appears multiple times in the reasoning content.

Consider using a combination of line content and index to ensure uniqueness:

-<div key={line} className="truncate">
+<div key={`${line}-${i}`} className="truncate">
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (4)

252-252: Potential concurrency check
Deleting the thread if the response status is ≥ 400 is correct to avoid orphaned data. Confirm that you handle concurrent calls so that you don't delete a thread that might still be in use.


301-301: Critical path error handling
Similar to line 252, ensure that deleteThread won't remove a valid thread in multi-request scenarios. Adding a check on activeThread?.messages.length or a cancellation token might help.


430-430: Duplicated retrieval logic
You're calling getCurrentSearchParams() here, but also performing a new URLSearchParams(...) operation in earlier lines. Evaluate if you can unify them for clarity.


800-803: Redundant param retrieval
getCurrentSearchParams is called again to extract isContinuingThread and continuousThreadId. If this logic is repeated in multiple places, consider caching or storing it in state.

apps/masterbots.ai/components/routes/chat/chat-message.tsx (1)

11-11: Confirm minimal usage of useState
The direct addition of useState for references is straightforward. Make sure to confirm if referencing or storing references in another context is beneficial for reusability.

apps/masterbots.ai/components/ui/codeblock.tsx (1)

125-125: Ensure correct z-index
Adding z-10 to the container might fix layering issues. Just confirm that it does not overshadow elements that should appear above the code block.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27b72ff and b063527.

📒 Files selected for processing (25)
  • apps/masterbots.ai/app/b/[botSlug]/[threadSlug]/page.tsx (0 hunks)
  • apps/masterbots.ai/app/u/[userSlug]/t/[category]/[domain]/[chatbot]/[threadSlug]/page.tsx (3 hunks)
  • apps/masterbots.ai/components/auth/signin-form.tsx (1 hunks)
  • apps/masterbots.ai/components/auth/signup-form.tsx (1 hunks)
  • apps/masterbots.ai/components/layout/profile/profile-page-sidebar.tsx (2 hunks)
  • apps/masterbots.ai/components/layout/sidebar/sidebar-link.tsx (3 hunks)
  • apps/masterbots.ai/components/routes/browse/browse-chat-message.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/browse/browse-chat-messages.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/chat/chat-message.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/chat/chat-panel.tsx (3 hunks)
  • apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx (4 hunks)
  • apps/masterbots.ai/components/routes/thread/thread-component.tsx (1 hunks)
  • apps/masterbots.ai/components/routes/thread/thread-popup.tsx (2 hunks)
  • apps/masterbots.ai/components/shared/feature-toggle.tsx (1 hunks)
  • apps/masterbots.ai/components/shared/loading-indicator.tsx (2 hunks)
  • apps/masterbots.ai/components/shared/shared-accordion.tsx (1 hunks)
  • apps/masterbots.ai/components/shared/short-message.tsx (1 hunks)
  • apps/masterbots.ai/components/shared/thread-blog-markdown.tsx (1 hunks)
  • apps/masterbots.ai/components/ui/codeblock.tsx (5 hunks)
  • apps/masterbots.ai/lib/hooks/use-copy-to-clipboard.tsx (1 hunks)
  • apps/masterbots.ai/lib/hooks/use-device.tsx (1 hunks)
  • apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (13 hunks)
  • apps/masterbots.ai/lib/memoized-markdown-components.tsx (1 hunks)
  • apps/masterbots.ai/lib/utils.ts (1 hunks)
  • apps/masterbots.ai/package.json (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/masterbots.ai/app/b/[botSlug]/[threadSlug]/page.tsx
🧰 Additional context used
🧠 Learnings (2)
apps/masterbots.ai/components/shared/thread-blog-markdown.tsx (1)
Learnt from: AndlerRL
PR: bitcashorg/masterbots#337
File: apps/masterbots.ai/components/shared/thread-blog-markdown.tsx:27-27
Timestamp: 2025-03-27T02:57:07.326Z
Learning: In react-markdown components, when list items contain paragraph tags causing unwanted line breaks, use CSS to style the paragraphs (e.g., `[&>p]:inline-block [&>p]:m-0`) instead of removing the semantic structure.
apps/masterbots.ai/lib/utils.ts (1)
Learnt from: AndlerRL
PR: bitcashorg/masterbots#425
File: apps/masterbots.ai/lib/utils.ts:308-308
Timestamp: 2025-03-28T21:43:52.984Z
Learning: The 'pro' route type was intentionally added to the RouteType definition before its implementation logic, as the complete implementation exists in a separate branch (feat-pro-layout). This reflects an incremental development approach where type definitions may be updated in advance of their full implementation.
🧬 Code Definitions (6)
apps/masterbots.ai/components/shared/thread-blog-markdown.tsx (2)
apps/masterbots.ai/components/shared/markdown.tsx (1)
  • MemoizedReactMarkdown (5-10)
apps/masterbots.ai/lib/memoized-markdown-components.tsx (1)
  • memoizedMarkdownComponents (54-217)
apps/masterbots.ai/components/shared/shared-accordion.tsx (1)
apps/masterbots.ai/lib/utils.ts (1)
  • cn (9-11)
apps/masterbots.ai/app/u/[userSlug]/t/[category]/[domain]/[chatbot]/[threadSlug]/page.tsx (1)
apps/masterbots.ai/lib/url.ts (1)
  • getCanonicalDomain (41-54)
apps/masterbots.ai/components/shared/loading-indicator.tsx (1)
apps/masterbots.ai/lib/hooks/use-device.tsx (1)
  • useDevice (9-39)
apps/masterbots.ai/lib/memoized-markdown-components.tsx (2)
apps/masterbots.ai/lib/utils.ts (1)
  • cn (9-11)
apps/masterbots.ai/components/ui/codeblock.tsx (1)
  • CodeBlock (197-197)
apps/masterbots.ai/components/routes/chat/chat-message.tsx (1)
apps/masterbots.ai/lib/memoized-markdown-components.tsx (1)
  • memoizedMarkdownComponents (54-217)
🔇 Additional comments (39)
apps/masterbots.ai/components/auth/signin-form.tsx (1)

35-35: Navigation path updated for consistency.

The redirection after successful sign-in has been changed from root path to '/c'. This aligns with the same change in the signup form, creating consistent post-authentication navigation flow.

apps/masterbots.ai/components/auth/signup-form.tsx (1)

97-97: Navigation path updated for consistency.

The redirection after successful signup has been changed from root path to '/c'. This aligns with the same change in the signin form, creating consistent post-authentication navigation flow.

apps/masterbots.ai/components/routes/thread/thread-component.tsx (1)

73-73: Simplified arrow styling for better maintainability.

The arrow class has been simplified from complex positioning to just width constraints. This reduces styling complexity while maintaining necessary functionality.

apps/masterbots.ai/components/shared/feature-toggle.tsx (1)

109-111:

Details

❓ Verification inconclusive

Verify impact of removing the label text.

The label text has been removed while keeping the empty Label component. This might impact accessibility for users who rely on visible labels rather than tooltips.

Could you confirm if:

  1. The tooltip provides sufficient context without the visible label?
  2. The icon alone gives enough visual indication of the toggle's purpose?
  3. This change maintains accessibility compliance?

🏁 Script executed:

#!/bin/bash
# Check if there are any references to the tooltip message being used for accessibility
rg -A 2 "aria-label" --glob "*.tsx" apps/masterbots.ai/components/

Length of output: 4898


Accessibility Impact: Verify Tooltip and Icon Effectiveness

It appears that no explicit accessibility attributes (like an aria-label) have been added to the empty Label component in feature-toggle.tsx, and there isn’t an indication from the tooltip search that extra accessibility context is configured for this particular component. Please ensure:

  • The tooltip (if used) delivers a clear and accessible description of the toggle’s purpose.
  • The icon is supplemented with appropriate accessibility attributes (e.g., aria-label or aria-labelledby) so that assistive technologies can interpret its function.
  • Overall, the modifications maintain compliance with accessibility standards, especially for users who benefit from visible labels.
apps/masterbots.ai/components/routes/chat/chat-panel.tsx (2)

68-68: Good addition of linter directive.

The linter directive is correctly added to suppress the warning about using the any type.


167-167: UI improvement with shorter button text.

Nice simplification from "Regenerate response" to just "Regenerate" - makes the UI more concise while maintaining clarity.

apps/masterbots.ai/components/layout/sidebar/sidebar-link.tsx (3)

244-244: Good addition of Pro route type detection.

The new isPro variable correctly checks if the current route type is 'pro', which aligns with the type definition changes in utils.ts.


275-284: Improved route type handling in navigation parameters.

The updated navigation logic now appropriately checks for the 'pro' route type first before falling back to public/personal checks. This ensures consistent routing behavior for pro users.


307-307: Consistent pro route type implementation.

The same logic for handling the 'pro' route type is consistently applied here in the URL builder parameters, ensuring that both navigation calls handle pro routes in the same way.

apps/masterbots.ai/components/shared/short-message.tsx (1)

1-1: Good refactoring to use centralized markdown components.

Excellent refactoring to use the memoizedMarkdownComponents() function instead of defining components inline. This promotes code reuse, ensures consistent rendering across components, and makes the code more maintainable.

Also applies to: 12-12

apps/masterbots.ai/lib/utils.ts (1)

308-308: Appropriate addition of 'pro' to RouteType.

Adding 'pro' to the RouteType definition is appropriate and aligns with the PR objectives to enhance various components. I notice from the retrieved learning that this type was intentionally added before its full implementation logic, which exists in a separate branch.

apps/masterbots.ai/components/shared/thread-blog-markdown.tsx (1)

1-12: Great refactoring to centralize markdown components!

Replacing the inline components definition with the memoized implementation improves code maintainability and ensures consistent rendering across the application. This change aligns with the DRY principle by centralizing markdown rendering logic.

apps/masterbots.ai/components/routes/browse/browse-chat-messages.tsx (1)

112-120: Nice UX improvement with back navigation

Adding a back navigation element improves the user experience by providing an easy way to return to the chatbot page. The sticky positioning ensures it remains accessible while scrolling.

One minor suggestion - consider using the buttonVariants utility that's already imported to style this link consistently with other navigation elements:

-					className="flex items-center leading-none gap-2 dark:text-white/80 text-[#09090BC3] dark:hover:text-white hover:text-[#09090B]"
+					className={cn(
+						buttonVariants({ variant: 'ghost', size: 'sm' }),
+						"flex items-center leading-none gap-2"
+					)}
apps/masterbots.ai/components/shared/loading-indicator.tsx (2)

1-9: Good enhancement for responsive design

Using the useDevice hook to detect mobile devices is a clean approach to providing a better user experience on different screen sizes.


15-39: Well-implemented device-specific messages

The separation of desktop and mobile messages with shorter text for mobile devices is a thoughtful enhancement that improves readability on smaller screens.

apps/masterbots.ai/components/shared/shared-accordion.tsx (1)

325-346: Improved layout structure with flexbox

The restructuring of the trigger button content using flexbox provides better alignment and more reliable positioning of elements. The new approach with nested flex containers ensures proper spacing and responsive behavior.

apps/masterbots.ai/app/u/[userSlug]/t/[category]/[domain]/[chatbot]/[threadSlug]/page.tsx (3)

7-7: Good addition of navigation elements

Adding the ChevronLeft icon and Link component improves navigation capabilities.

Also applies to: 11-11


25-26: Proper parameter extraction and URL construction

The destructuring of parameters and construction of the profileUrl creates a clean approach to building the navigation path.

Also applies to: 39-39


41-57: Enhanced user experience with back navigation

The addition of a back navigation link improves the user experience by providing a clear way to return to the profile page. The sticky positioning ensures the navigation remains accessible.

apps/masterbots.ai/components/routes/thread/thread-popup.tsx (2)

123-124: Enhanced responsive design with media queries

Changing from fixed padding (!px-[16px], !px-[32px]) to responsive padding using media queries (md:px-[16px], md:px-[32px]) improves the component's adaptability across different screen sizes.


215-215: Improved mobile responsiveness

Adding px-4 as a base padding with md:px-[32px] for larger screens creates a better experience on mobile devices while maintaining the original design on desktop.

apps/masterbots.ai/package.json (1)

65-65:

Details

✅ Verification successful

Consistent dependency updates

Good updates to Next.js and React dependencies, keeping them on the latest minor versions.

Also applies to: 71-71, 73-73, 94-94, 100-100


🌐 Web query:

Are there any breaking changes in Next.js 15.2.4 or React 19.1.0 compared to previous versions?

💡 Result:

Next.js 15.2.4 and React 19.1.0 introduce specific changes, though most breaking changes originated in their major releases (Next.js 15 and React 19). Here's a breakdown:


Next.js 15.2.4 Breaking Changes

This patch release primarily backports fixes, but includes targeted adjustments:

  • Middleware Origin Checks:
    • Subrequest handling now matches between Edge and Node.js environments[10].
    • Excludes images/static media from development origin checks[10].
    • Removes direct IP/port bypass in development origin verification[10].
    • Origin check logic is now opt-in instead of opt-out[10].
      Applications relying on implicit origin checks may need adjustments.

React 19.1.0 Breaking Changes

As a minor release, React 19.1.0 does not introduce new breaking changes beyond those in React 19.0.0. Key React 19 breaking changes include:

  1. New JSX Transform Required:
    • Apps must use the updated JSX transform for features like ref as a prop[2][11].
  2. Error Handling:
    • Uncaught errors are reported via window.reportError (not rethrown)[2][11].
    • Custom error handling via onCaughtError/onUncaughtError in createRoot[11].
  3. Deprecated API Removals:
    • propTypes, defaultProps (for functions), string refs, React.createFactory, and legacy context APIs[2][11].
  4. StrictMode Changes:
    • Memoization (useMemo, useCallback) behavior adjusted during double renders[11].

Key Next.js 15 Breaking Changes (Original Major Release)

While Next.js 15.2.4 itself has minimal breaks, the broader Next.js 15 release included:

  • Caching Defaults:
    • fetch, GET Route Handlers, and client navigations no longer cached by default[1][7].
  • Image Optimization:
    • sharp replaces squoosh (requires manual installation if using)[1][6].
  • Middleware Restrictions:
    • Blocks React Server imports in Middleware[1].
  • Font System Updates:
    • Removed font-family hashing and external @next/font package[1].
  • Config Defaults:
    • Enabled swcMinify, outputFileTracing, and others by default[1].

Migrating Tips

  • Next.js: Use npx @next/codemod@canary upgrade latest for automated fixes[7].
  • React 19: Update dependencies and replace deprecated APIs (e.g., useFormStateuseActionState)[7][11].

For detailed migration guides, refer to Next.js's Upgrade Guide and React's 19 Upgrade Documentation.

Citations:


Verified Dependency Updates: Next.js 15.2.4 & React 19.1.0

The dependency updates in apps/masterbots.ai/package.json are consistent improvements overall. Notably:

  • Next.js 15.2.4: This patch introduces some targeted changes—specifically, middleware origin checks have shifted to an opt-in mode. This should not affect most applications unless you rely on the previous implicit behavior.
  • React 19.1.0: As a minor release, it carries forward the breaking changes established in React 19.0.0 without adding new ones, ensuring a smooth upgrade.

These updates (applied at lines 65, 71, 73, 94, and 100) are safe to merge. However, if your application uses Next.js middleware heavily, please verify that the new origin check behavior aligns with your requirements.

apps/masterbots.ai/components/routes/chat/reasoning/reasoning-chat-message.tsx (3)

7-14: Clean import organization

Good reorganization of imports to include the new memoized components and simplify icon usage.


79-79: Improved UI labeling and rendering

The UI text changes from "AI Thinking Process" to "Reasoning" and "Final Answer" to "Answer" make the interface clearer and more concise. Using the ChevronsDownUp icon simplifies the toggle button implementation.

Also applies to: 86-86, 96-96, 122-122


128-131: Excellent use of centralized markdown components

Good implementation of the new memoizedMarkdownComponents function, which enhances code maintainability by centralizing Markdown rendering logic.

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

173-175: Double-check fallback logic for thread ID
When isContinuousThread is false, the thread ID defaults to activeThread?.threadId || randomThreadId.current. Ensure this does not override existing thread IDs in mid-conversation scenarios and inadvertently start a new thread.

Would you confirm whether activeThread?.threadId is always set for existing threads or if there's a risk of returning a random ID unexpectedly?


187-187: Conditional thread ID usage
Returning threadId for new chats is logical. Just be aware that if threadId is not set, it might cause confusion or fallback to the random ID.


220-220: Unique id property
Using threadId as the id in useChatOptions helps isolate chat sessions. Ensure threadId remains stable across re-renders, so the chat state isn't reset prematurely.


470-470: Ensure correct thread deletion
In the onError callback, you're deleting the thread if it's a new chat. Confirm that partial updates or other side effects have not occurred before.


528-553: Validate message sorting logic
You are handling chronological order and role-based ordering for identical timestamps. This approach looks sound, but be cautious about potential ties if there's more than one user message with the same timestamp. Since you rely on chronological order as primary sorting, ensure the timestamps are unique or use a stable ID fallback.


784-784: Inconsistent id usage
Passing id: activeThread?.threadId in the appended message may conflict if the user intended a new random thread. Verify that the id matches the rest of the thread logic.


100-100:

Details

❓ Verification inconclusive

Ensure route definitions align with typed params
The typed usage of chatbot and threadSlug is helpful for clarity. Confirm that the route structure in Next.js matches these param names to avoid mismatch errors.

As a follow-up, you can run the following search to check for references to those params:


🏁 Script executed:

#!/bin/bash
# Searching for dynamic route definitions that reference [chatbot] and [threadSlug]
fd 'page\.[jt]sx$' | xargs rg "export default function"
rg -A 5 "router\.push"

Length of output: 10419


Action: Confirm Next.js dynamic route names match the typed parameters

The use of

const params = useParams<{ chatbot: string; threadSlug: string }>()

is clear and improves type safety. However, please verify that your Next.js dynamic route files (for example, the ones handling chat or thread views) use matching dynamic segment names (i.e. [chatbot] and [threadSlug]) to ensure there are no runtime mismatches. The repository search didn’t return any conflicting implementations, but a manual check of the relevant route files is recommended.

apps/masterbots.ai/components/routes/chat/chat-message.tsx (2)

8-8: Centralize Markdown logic
Importing memoizedMarkdownComponents aligns with your code reuse strategy. This reduces duplication of markdown and ensures consistent rendering.


92-95: Customize rendered Markdown
By providing handleClickableClick and shouldPreProcessChildren, you can add interactive behavior to the markdown. Double-check if heavy preprocessing is required or can be toggled.

apps/masterbots.ai/components/ui/codeblock.tsx (5)

28-79: Expanded language support
Adding multiple languages to programmingLanguages improves coverage for code samples. Confirm that each addition is valid and that the syntax highlighter is able to handle them all.


93-99: Prevent event propagation
Preventing propagation in downloadAsFile is good for embedded usage, ensuring no parent click handlers are triggered. Also, randomizing the file name extension helps disambiguate user downloads.


118-119: Stop click event on copy
Stopping event propagation is a neat approach to avoid conflicts with parent's onClick. Well done.


136-136: Pointer events
Adding pointer-events-auto ensures the button is clickable even if the parent might have interfering styles. Confirm that the rest of the UI is unaffected.


146-146: Pointer events
Same reasoning as line 136. This ensures the copy button remains clickable.

@AndlerRL AndlerRL merged commit 5fc400b into main Apr 1, 2025
2 checks passed
@AndlerRL
Copy link
Member Author

AndlerRL commented Apr 2, 2025

@AndlerRL
Copy link
Member Author

AndlerRL commented Apr 2, 2025

This was referenced Jul 22, 2025
sheriffjimoh added a commit that referenced this pull request Sep 9, 2025
…md (#428)

* fix: change toggler wording + util hook (#424)

* impr: makes threads open on profile page and profile tweaks (#421)

* update

* fix: update

* update

* update

* update

* update

* fix: opening threads

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: update

* fix: added back to profile page

* fix: added sticky and color

* fix: codeblock ctas refactor markdown rendering, sidebar nav, code block & clipboard hook (#425)

* fix: codeblock ctas

* fix: ts build

* fix: continue thread + allMessages sequence + mobile chat css tweak (#426)

* fix: css handleCLick condition

* fix: get latest search params, continuous thread

* fix(impr): all messages sorting

* perf(impr): sign in & up redirection tweak

* perf(impr): mobile chat css

* chore: next + react security ver upt (#427)

---------

Co-authored-by: Brandon Fernández <31634868+Bran18@users.noreply.github.com>
Co-authored-by: Jimoh sherifdeen <63134009+sheriffjimoh@users.noreply.github.com>
sheriffjimoh added a commit that referenced this pull request Sep 10, 2025
…md (#428)

* fix: change toggler wording + util hook (#424)

* impr: makes threads open on profile page and profile tweaks (#421)

* update

* fix: update

* update

* update

* update

* update

* fix: opening threads

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: rm threads dropdwon  & added back link to bot page thread view page

* fix: update

* fix: added back to profile page

* fix: added sticky and color

* fix: codeblock ctas refactor markdown rendering, sidebar nav, code block & clipboard hook (#425)

* fix: codeblock ctas

* fix: ts build

* fix: continue thread + allMessages sequence + mobile chat css tweak (#426)

* fix: css handleCLick condition

* fix: get latest search params, continuous thread

* fix(impr): all messages sorting

* perf(impr): sign in & up redirection tweak

* perf(impr): mobile chat css

* chore: next + react security ver upt (#427)

---------

Co-authored-by: Brandon Fernández <31634868+Bran18@users.noreply.github.com>
Co-authored-by: Jimoh sherifdeen <63134009+sheriffjimoh@users.noreply.github.com>
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.

3 participants