Skip to content

Enhance user preferences, update database schema, and improve UI components#495

Merged
AndlerRL merged 66 commits intomainfrom
develop
May 24, 2025
Merged

Enhance user preferences, update database schema, and improve UI components#495
AndlerRL merged 66 commits intomainfrom
develop

Conversation

@AndlerRL
Copy link
Member

@AndlerRL AndlerRL commented May 24, 2025

Summary by Sourcery

Overhaul subscription and chat UI with animated, data-driven components; extend image generation support end-to-end by introducing an examples field, updating schemas, migrations, and enums; refine image display and AI call logic; customize user profile and empty states; and implement various type, metadata, and auth slug improvements.

New Features:

  • Revamp subscription page with animated sections for current plan, pro benefits, payment method, and transaction history
  • Add support for storing and rendering generated image examples in chat messages via a new examples field and memoized image section
  • Introduce new AI image models to Hasura schema and GraphQL enums (gpt-image-1, dall-e-2/3, gemini-2.0-flash-exp)
  • Customize EmptyState component props and display pro badge in user profiles
  • Generate unique user slugs by appending timestamps during authentication

Enhancements:

  • Enhance GeneratedImage component with loading/error states, improved download logic, and UI polish
  • Filter core messages for Gemini flash-exp model and enable image modalities in AI main call
  • Disable preference toggles with visual feedback and adjust styling for disabled state
  • Apply minor layout and styling tweaks across components (dark mode, padding adjustments)

Chores:

  • Add current_period_end to subscription types and update related migrations
  • Add deletion_requested_at field to Hasura public_user metadata
  • Update Hasura migration scripts for new AI model enums

Summary by CodeRabbit

  • New Features

    • Added support for updating user preferences, including toggling "Always Web Search" and "Always Pro Mode" options.
    • Enhanced subscription management page with animated UI, payment method details, and transaction history.
    • Expanded user profile display with badges for Pro users and improved empty state messaging.
    • Added over 60 new domain topics for chatbot categorization.
    • Introduced new AI model variants and updated existing model options.
  • Improvements

    • User preferences are now automatically created and updated during signup and authentication.
    • Image generation and display in chat enhanced with better error handling and default settings.
    • Chat sharing now provides clearer feedback with tooltips.
    • Filtering and UI logic for thread sharing and approval made more intuitive.
    • Preference and profile sections support dark mode and improved accessibility.
  • Bug Fixes

    • Fixed issues with preference updates not reflecting immediately.
    • Addressed inconsistencies in chat image rendering and sharing.
  • Chores

    • Upgraded backend schema and dependencies for improved reliability and future features.
    • Refactored and consolidated backend database schema for better maintainability.

Bran18 and others added 30 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
…ck (#432)

* refactor: use chat and continue generation

* fix: uniq slug and id gen (#433)

* fix: uniq thread + msg slug gen

* style: formatting

* fix: thread user attachments state upt

* perf: impr thread component at all pages + mobile tweaks

* refactor: thread-component card

* chore: restore continue generation v1

* feat(impr): thread component card

* fix: admin panel n actions

* fix: fetch getThreads

* chore: continue conversation v1.2

* chore: continue and update thread content

* chore: add ui control continue generation state

* chore: fix infinity loop

* chore(impr): enable upt msg table permission

* fix: seo thread fetch

* chore: style formating

* fix(impr): continued thread title + thread component reusability

* chore: refactor loadings + extending sonners

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>
* feat: add gemini provider

* chore: update icons
* feat(wip): impr continuing thread tags + accordion first msg toggle

* feat(impr): continuing thread tags + accordion at first message + header mobile tweak

* style(impr): mobile thread-component x-axis space

* perf(style): coderabbitai feedbacks

* fix: css typo

* perf: sendMessageFromResponse clicked guard + continued thread tags label tweak

* chore: user thread panel clean up

* fix: user-thread-panel infinite loader

* perf: impr shared accordion animation and ux

* style: defaultAccordionState comments loc

* fix: record type warning, hasura updateMessage

* fix: getThread user data, shared-accordion
* update

* fix: update

* update

* update

* update

* update

* refactor: profile page threads pop up

* fix: update config

* fix: update

* fix: update

* fix: make profile page scroll on hero

* fix: bot make popup and scroll

* fix: make profile page sidebar scroll independently

* fix: make profile page sidebar scroll independently

* fix: check the category along the chatbot when it's not checked

* fix: check the category along the chatbot when it's not checked

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
Co-authored-by: Roberto Lucas <andler@bitcash.org>
* feat-add-models

* feat-add-models

* feat-add-models

* chore: add model

* fix: typo

* chore: add toggler color
… seeds (#447)

* feat(wip): thread llm context, prev questions

* fix: previousQuestionsString slice

* fix: clickedContentId in followingQuestionsPrompt

* feat: isContinued + model type in message table

* fix: ts typo + sendMessageFromResponse callback call

* fix: ts typo
* fix(wip): bot profile thread list

* style: formatting
* fix: new chat state reset

* fix: genql gen + share link check

* fix: og img

* fix: duplicate role permission in msg table
* chore: restore base version

* chore: add new logic and hooks

* chore: fix providers file

* chore: improve continuation prompt

* chore: add exlucision flag

* chore: add better handler

* chore: updated flow + experimental delay

* chore: extended time

* chore(impr): streamDelayMs experimental feat flag

* style: formatting

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
* fix: profile sidebar cat opt render

* chore: clean-up
…ess and type support (#456)

* fix: slugify fn

* chore: devMode logs
* fix: slugify first request delay incr + genql ts, seeds & model migration upt

* fix: create thread & msg ts
* update

* fix: update

* update

* update

* update

* update

* fix: use the user avatar or robohash

* fix: added avater to user menu

* fix: user avatar

* fix: reset search input when filter by category or chatbot

* fix: personal chat browse provider + username chk in sign up

* chore: clean duplicated if condition signup

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
* impr: continuation logic flow

* impr: continuation logic flow

* chore: update createImprovementPrompt

* chore: upt logs

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
…gic (#462)

* feat: models table

* style: formatting

* fix: continuation accordion content

* fix: sql + metadata typo
AndlerRL and others added 12 commits May 14, 2025 17:04
* chore: hasura, set icl seeds chunks

* chore: track backup icl seed loc to lfs

* chore(seeds): uncomment phase 3 topics & add new chatbots + icl metadata rel

* chore: upt phase 3 init config seeds, adding rel

* fix: example seeds integrity

* test: incr hasura max req body

* revert: cloudbuild og config

* chore: restore skipped seed lines
* fix: thread list render states

* chore: linting & format

* fix: thread pop-up on refresh

* fix: user table selection
#489)

* fix: image generation flow

* chore: impr gemini generation logic

* fix: build issue

* chore: change subscription page

* chore: change subscription page + lint

* chore: user pref disable options

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>
* feat: add improved subscription section

* feat: add type

* chore: add conditional dislay

* feat: add username tags

* chore: add new order and benefits
* update

* fix: update

* update

* update

* update

* update

* feat: added empty state to user profile page

* feat: added empty state to user profile page

* fix: update

* fix: update

* fix: account creation slug issue

* chore: restore public models table select permissions + clean up

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>
Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
@AndlerRL AndlerRL self-assigned this May 24, 2025
@vercel
Copy link

vercel bot commented May 24, 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 May 24, 2025 9:17am

@sourcery-ai
Copy link

sourcery-ai bot commented May 24, 2025

Reviewer's Guide

This PR enriches the subscription experience with a fully animated subscription page powered by Framer Motion and usePayment hook integration, enhances image generation display and error handling, refines AI helper functions and chat rendering to use a new examples-based structure, updates UI preferences to a read-only state, synchronizes model enums and database migrations for new AI image models, strengthens slug generation in authentication, and polishes various UI components for consistency and dark-mode support.

Sequence Diagram for Subscription Page Data Loading

sequenceDiagram
    participant Client as SubscriptionPageComponent
    participant usePaymentHook as usePayment()
    participant Backend as fetchPayment Action
    participant ExternalAPI as Stripe API/DB

    Client->>usePaymentHook: Get paymentIntent
    usePaymentHook-->>Client: Returns paymentIntent
    alt paymentIntent exists
        Client->>Backend: fetchPayment(paymentIntent)
        Backend->>ExternalAPI: Retrieve subscription details
        ExternalAPI-->>Backend: Subscription data
        Backend-->>Client: Returns subscriptionData (value)
    end
Loading

Sequence Diagram for New User Registration and Slug Generation

sequenceDiagram
    actor User
    participant NextAuthProvider as NextAuth Provider
    participant AuthLogic as auth.ts (signIn callback)
    participant Database

    User->>NextAuthProvider: Initiates Sign-In/Sign-Up
    NextAuthProvider->>AuthLogic: Process user (e.g., OAuth callback)
    AuthLogic->>Database: Check if user exists (findUserByEmail)
    Database-->>AuthLogic: User not found
    Note over AuthLogic: New user: Generate slug with timestamp and username
    AuthLogic->>AuthLogic: toSlug(userName) + "-" + timestamp
    AuthLogic->>AuthLogic: generateUsername(emailPrefix or userName)
    AuthLogic->>Database: Create new user record (with unique slug, username)
    Database-->>AuthLogic: User record created
    AuthLogic-->>NextAuthProvider: User processed
    NextAuthProvider-->>User: Session created, user logged in
Loading

ER Diagram for User and Subscription Data Model Updates

erDiagram
    User {
        string id PK
        string email
        string username
        datetime deletion_requested_at
        string pro_user_subscription_id
        string slug
        string stripe_customer_id
        string stripe_price_id
        string stripe_subscription_id
    }

    Subscription_TS_Type {
        string id
        string user_id
        object product_details "{ id, name, description, image }"
        number current_period_start
        number current_period_end
        string status
    }
    User ||--o{ Subscription_TS_Type : "has subscription information as"
Loading

Updated Class Diagram for Subscription Data Type

classDiagram
    class Subscription {
        +id: string
        +user_id: string
        +product: ProductDetails
        +current_period_start: number
        +current_period_end: number
        +status: string
    }
    class ProductDetails {
      +id: string
      +name: string
      +description: string
      +image: string
    }
    Subscription "1" -- "1" ProductDetails : contains
Loading

Class Diagram for New Chat Image Data Types

classDiagram
    class StoredImagePart {
        <<Type>>
        +type: "file" | "image"
        +data: string
        +mimeType: string
    }
    class MBMessage {
        <<BaseType>>
        # existing MBMessage fields...
    }
    class MessageWithExamples {
        <<Type>>
        +examples?: StoredImagePart[]
    }
    MessageWithExamples --|> MBMessage : extends
    MessageWithExamples "1" o-- "*" StoredImagePart : contains
Loading

Updated Class Diagram for GeneratedImage Component

classDiagram
    class GeneratedImage {
        <<Component>>
        +base64: string
        +mimeType: string
        +alt: string
        -isLoading: boolean
        -error: string | null
        +useEffect()
        +handleDownload()
        +handleError()
    }
    note for GeneratedImage "mimeType and alt have new default values.
    error state and handleError method are new.
    useEffect resets loading/error on base64 change."
Loading

Updated Class Diagram for EmptyState Component

classDiagram
    class EmptyState {
        <<Component>>
        +title: string
        +description: string
    }
    note for EmptyState "Props title and description are new (or made customizable with defaults)."
Loading

Updated Class Diagram for AIHelpers Module

classDiagram
  class AIHelpers {
    <<Module>>
    +hasImageGeneration(message: MessageWithExamples): boolean
    +extractImageContent(message: MessageWithExamples): StoredImagePart[]
  }
  AIHelpers ..> MessageWithExamples : uses
  AIHelpers ..> StoredImagePart : uses
  note for AIHelpers "Function signatures updated to use MessageWithExamples and StoredImagePart."
Loading

File-Level Changes

Change Details Files
Animated subscription page with payment and plan management
  • Imported and used fetchPayment, useSession, useAsync, and usePayment hook
  • Defined Framer Motion variants and wrapped UI sections with motion components
  • Conditionally rendered current plan, upgrade flows, pro benefits, payment method, and transaction history
  • Linked to detailed invoice view using dynamic routing
  • Toggled Subscription component on user interaction
subscription-page.tsx
Enhanced GeneratedImage component with loading, error handling, and download UX
  • Added useEffect to reset loading/error on source change
  • Introduced error state and onError handler with fallback UI
  • Switched to unoptimized Next/Image with priority loading and opacity transition
  • Overlayed loader and group-hover download button
generated-image.tsx
Refactored AI helper functions and chat message image rendering
  • Changed hasImageGeneration and extractImageContent to use examples array, with logging
  • Mapped StoredImagePart to base64/mimeType pairs safely
  • Wrapped image section in useMemo, added stable keys and console warnings
  • Updated MBChatProvider to populate examples instead of files
ai-helpers.ts
chat-message.tsx
use-mb-chat.tsx
Disabled interactive sections in preferences UI
  • Set toggles and toggle groups to disabled with reduced opacity
  • Marked add icons as non-clickable
  • Reordered utility classes for consistency
preference-section.tsx
Synchronized model enums, database migrations, and GraphQL types for new AI image models
  • Added new entries for image models in migrations and public_models seed
  • Expanded AIModels enum with latest identifiers
  • Extended Subscription type and initial state with current_period_end
  • Defined StoredImagePart and MessageWithExamples types
migrations/masterbots/*_create_table_models_enum/up.sql
migrations/masterbots/*_create_table_public_models/up.sql
types.ts
models.ts
Improved slug generation in NextAuth registration
  • Appended base36 timestamp to generated user slug
auth.ts
Polished UI components for consistency and dark mode support
  • Made EmptyState configurable with title/description and dark text
  • Prefixed username with @ and lowercased, added pro badge in UserCard
  • Adjusted profile layout padding ordering
empty-state.tsx
user-card.tsx
layout.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!

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 24, 2025

Walkthrough

This update introduces major enhancements to user preference management, database schema, and application logic. It adds new preference fields, updates permissions, and ensures preferences are initialized on signup and authentication. The database schema is restructured using Drizzle ORM, with expanded enums and tables. UI components are improved for subscription management, image handling, and user feedback.

Changes

Files/Groups Change Summary
apps/hasura/metadata/databases/masterbots/tables/public_preference.yaml, related migrations Added/updated insert, select, and update permissions for "moderator" and "user" roles; added deep_expertise and web_search columns; removed chatbot_id from permissions; enforced unique constraint on user_id.
apps/hasura/metadata/databases/masterbots/tables/public_user.yaml Added preference object relationship; allowed deletion_requested_at updates for "moderator" and "user" roles.
apps/hasura/migrations/... (multiple up/down SQL files) Added columns web_search, deep_expertise to preference; made chatbot_id nullable with default; added/removes constraints; updated enum/data for models.
apps/hasura/seeds/masterbots/1724270512560_init_users_seeds.sql Updated Git LFS pointer metadata.
apps/masterbots.ai/app/actions/ai-executers.ts Commented out getWebSearchTool function and related imports, marking for future removal.
apps/masterbots.ai/app/actions/ai-main-call.ts Adjusted AI tool configuration, added streaming parameters, and customized Gemini model message handling.
apps/masterbots.ai/app/api/auth/signup/route.ts Ensured user preferences are created on signup; aborts signup if preference creation fails.
apps/masterbots.ai/app/api/chat/models/models.ts Split and updated AIModels enum entries for new Gemini model variants.
apps/masterbots.ai/app/u/[userSlug]/layout.tsx Reordered CSS class names; no functional change.
apps/masterbots.ai/auth.ts Added ensureUserPreferences function, invoked after JWT and Google sign-in; refactored user creation and slug generation logic.
apps/masterbots.ai/components/routes/chat/chat-message.tsx Refactored image section to use useMemo and stable keys; improved image rendering and error handling.
apps/masterbots.ai/components/routes/chat/chat-options.tsx Refined dropdown item rendering logic for thread approval and sharing.
apps/masterbots.ai/components/routes/chat/share-button.tsx Added tooltip for copy status feedback on share button.
apps/masterbots.ai/components/routes/preferences/preference-section.tsx Added async preference update logic for switches; disabled toggle group; improved UI feedback.
apps/masterbots.ai/components/routes/preferences/preferences.tsx Simplified filtering logic for preference sections.
apps/masterbots.ai/components/routes/profile/empty-state.tsx Made EmptyState component props customizable; improved dark mode support.
apps/masterbots.ai/components/routes/profile/user-card.tsx Rendered username as lowercase with badge for pro users.
apps/masterbots.ai/components/routes/subscription/subscription-page.tsx Major UI/UX overhaul: added animated sections, payment/subscription details, and conditional rendering based on user state.
apps/masterbots.ai/components/routes/thread/user-thread-panel.tsx Rendered explicit empty state for profile page when no threads exist.
apps/masterbots.ai/components/shared/generated-image.tsx Improved image error/loading handling, default MIME type, and download logic; enhanced UI.
apps/masterbots.ai/lib/constants/domain-slugs.ts Added 60+ new domain slugs to the exported array.
apps/masterbots.ai/lib/constants/preferences.ts Added props object with switchId and switchName to preference items.
apps/masterbots.ai/lib/constants/prompts.ts Updated output instructions to guide web search tool use and handling out-of-scope questions.
apps/masterbots.ai/lib/helpers/ai-helpers.ts Refactored image extraction logic to use examples array; updated types and logging.
apps/masterbots.ai/lib/helpers/ai-schemas.ts Commented out webSearch tool; removed related imports.
apps/masterbots.ai/lib/hooks/use-mb-chat.tsx Changed file part handling from image to file type; used examples array for assistant messages.
apps/masterbots.ai/lib/hooks/use-thread.tsx Fetched user data asynchronously to initialize web search state from preferences.
apps/masterbots.ai/services/admin/admin.service.ts Switched to new user, userRole, preference tables; added insertAdminUserPreferences function; updated types and logic.
apps/masterbots.ai/services/hasura/hasura.service.ts Added updatePreferences and insertPreferencesByUserId functions; extended getUserBySlug to include preferences.
apps/masterbots.ai/types/types.ts Updated/added types for preferences, images, and enums; removed CoreMessage; updated StreamTextParams and AdminUserUpdate.
packages/mb-drizzle/drizzle.config.ts, package.json Updated Drizzle config for new schema location, dialect, and dependencies.
packages/mb-drizzle/drizzle/0001_round_malcolm_colcord.sql, meta/0001_snapshot.json, ... Deleted old schema/migration files for previous user/auth structure.
packages/mb-drizzle/src/drizzle/0000_pink_lionheart.sql, meta/0000_snapshot.json, ... Added new comprehensive schema and snapshot files defining all tables, enums, and relations.
packages/mb-drizzle/src/drizzle/relations.ts, schema.ts, index.ts Added/updated ORM relations and schema exports for new database structure.
packages/mb-drizzle/src/schema/auth.ts, index.ts Deleted old auth schema and re-export files.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant API
  participant Hasura
  participant DB

  User->>API: Sign up or Authenticate
  API->>Hasura: Insert user record
  Hasura->>DB: Create user row
  Hasura-->>API: Return user ID
  API->>Hasura: Insert user preferences (default values)
  Hasura->>DB: Create preference row
  Hasura-->>API: Return preference data
  API-->>User: Complete sign up/authentication
Loading
sequenceDiagram
  participant User
  participant UI
  participant API
  participant Hasura
  participant DB

  User->>UI: Toggle preference switch
  UI->>API: updatePreferences(jwt, userId, preferencesSet)
  API->>Hasura: GraphQL mutation to update preference
  Hasura->>DB: Update preference row
  Hasura-->>API: Return updated preference data
  API-->>UI: Show success or error notification
Loading

Possibly related PRs

  • bitcashorg/masterbots#444: Updates AIModels enum with new Gemini model variants, directly relating to similar enum changes in this PR.
  • bitcashorg/masterbots#494: Modifies public.preference table permissions, including deep_expertise and web_search columns, closely matching this PR's permission updates.
  • bitcashorg/masterbots#260: Alters authentication flow and user creation logic in auth.ts, which is also updated in this PR.

Suggested labels

enhancement, feature, backend, ui/ux, chore

Poem

A bunny hopped through fields of code,
Planting preferences where users strode.
With tables fresh and enums bright,
And toggles switching left and right.
Now signups bloom with choices fair,
While Drizzle rains new schema air—
The garden grows, with care, delight, and flair!

((\
( -.-)
o_(")(")

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/app/actions/ai-executers.ts

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/actions/ai-main-call.ts

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/api/auth/signup/route.ts

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.

  • 23 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

* feat(wip): web search

* feat(wip): thread config actions

* feat(wip): share cta impr

* chore: upt domain slugs list

* chore: comment legacy getWebSearchTool

* fix: preference insert

* wip: user preferences set

* fix: typo

* fix: updateUser data upt
@AndlerRL
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 24, 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.

@coderabbitai coderabbitai bot changed the title @coderabbitai Enhance user preferences, update database schema, and improve UI components May 24, 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: 22

🔭 Outside diff range comments (2)
apps/hasura/migrations/masterbots/1747220030651_alter_table_public_preference_add_column_deep_expertise/down.sql (1)

1-5: ⚠️ Potential issue

Critical: Implement correct down migration to drop deep_expertise.
The stub currently instructs to add the column; instead, the down migration should remove it. For example:

ALTER TABLE "public"."preference"
  DROP COLUMN IF EXISTS "deep_expertise";
apps/hasura/migrations/masterbots/1747220015500_alter_table_public_preference_add_column_web_search/down.sql (1)

1-5: ⚠️ Potential issue

Critical: Missing rollback SQL in down migration.

This down migration file only contains comments but lacks the actual SQL to rollback the web_search column addition. This makes the migration incomplete and prevents proper rollbacks.

Add the following SQL to properly rollback the column addition:

-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."preference" add column "web_search" boolean
--  null default 'false';
+
+ALTER TABLE "public"."preference" DROP COLUMN "web_search";
🧹 Nitpick comments (18)
apps/hasura/migrations/masterbots/1748042391832_alter_table_public_preference_alter_column_user_id/down.sql (1)

1-1: Consider using IF EXISTS when dropping the constraint
Wrapping the DROP CONSTRAINT in IF EXISTS can prevent migration failures if the constraint is already absent.

apps/hasura/migrations/masterbots/1748071970273_alter_table_public_preference_alter_column_chatbot_id/down.sql (1)

1-1: Consider using IF EXISTS when dropping the default
Adding IF EXISTS guards against errors if the default has already been removed.

apps/hasura/migrations/masterbots/1748071543571_alter_table_public_preference_alter_column_chatbot_id/up.sql (1)

1-1: Standardize SQL keyword casing for readability
Consider uppercasing keywords (e.g., ALTER TABLE, DROP NOT NULL) to align with other migration scripts.

apps/hasura/migrations/masterbots/1747220015500_alter_table_public_preference_add_column_web_search/up.sql (1)

1-2: Use boolean literal and standard SQL syntax for default
Prefer DEFAULT false (without quotes) and place it before the NULL qualifier for clarity and consistency.
Example diff:

-alter table "public"."preference" add column "web_search" boolean
- null default 'false';
+ALTER TABLE "public"."preference"
+  ADD COLUMN "web_search" BOOLEAN DEFAULT false NULL;
apps/hasura/migrations/masterbots/1747220030651_alter_table_public_preference_add_column_deep_expertise/up.sql (1)

1-2: Use boolean literal and standard SQL syntax for default
Prefer DEFAULT false (without quotes) and move NULL after the default for consistency across migrations.
Example diff:

-alter table "public"."preference" add column "deep_expertise" boolean
- null default 'false';
+ALTER TABLE "public"."preference"
+  ADD COLUMN "deep_expertise" BOOLEAN DEFAULT false NULL;
apps/hasura/migrations/masterbots/1748071970273_alter_table_public_preference_alter_column_chatbot_id/up.sql (1)

1-1: Use numeric default for integer column.
If chatbot_id is an integer, prefer SET DEFAULT 1 (without quotes) to avoid implicit type casting.

apps/masterbots.ai/components/routes/preferences/preferences.tsx (1)

10-10: Code simplification is good, but consider readability trade-offs.

The regex approach successfully simplifies the condition while maintaining the same logic. However, for just two string comparisons, the explicit approach might be more readable and performant.

If you prefer explicit comparisons for clarity:

-			(section.title.match(/(General|Thread Preferences)/) &&
+			(['General', 'Thread Preferences'].includes(section.title) &&
apps/masterbots.ai/app/actions/ai-executers.ts (1)

51-152: Appropriate deprecation approach for transitioning web search implementation.

The function is properly commented out with a clear TODO indicating removal timeline. This preserves the implementation for reference while the new web search tool is being integrated via OpenAI's web search preview.

Consider removing this commented code once the new web search implementation is fully tested and stable to reduce code clutter.

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

118-119: Remove or wrap console.log statements in development flag.

These debugging statements should not be in production code. Consider removing them or wrapping them in a development check.

-			console.log('No images extracted from message parts:', message.parts)
+			if (process.env.NODE_ENV === 'development') {
+				console.log('No images extracted from message parts:', message.parts)
+			}
-					console.warn(`Image ${i} has no base64 data`)
+					if (process.env.NODE_ENV === 'development') {
+						console.warn(`Image ${i} has no base64 data`)
+					}

Also applies to: 126-126

apps/masterbots.ai/auth.ts (1)

303-303: Update console.log message for clarity.

The message refers to "user profile" but the function is creating preferences.

-		console.log('user profile created: ', preference)
+		console.log('user preferences created: ', preference)
apps/masterbots.ai/app/actions/ai-main-call.ts (2)

337-337: Wrap console.log statements in development checks.

Debug logging should not appear in production.

-		console.log('🔵 webSearch tool activated')
+		if (process.env.NODE_ENV === 'development') {
+			console.log('🔵 webSearch tool activated')
+		}
-				console.log('isGemini2FlashExp -> 🤖 ', isGemini2FlashExp)
+				if (process.env.NODE_ENV === 'development') {
+					console.log('isGemini2FlashExp -> 🤖 ', isGemini2FlashExp)
+				}

Also applies to: 459-459


375-377: Clarify the workaround comment.

The comment about the workaround could be more descriptive to help future developers understand the purpose.

-							//? This is a workaround for the OpenAI API to not return the reasoning
+							//? This is a workaround to limit tool execution steps in non-reasoning models
+							//? to prevent excessive API calls and improve response consistency
apps/masterbots.ai/components/routes/subscription/subscription-page.tsx (1)

37-252: Consider splitting into smaller components

The component is quite large and handles multiple responsibilities. Consider extracting each section (Current Plan, Pro Benefits, Payment Method, Transaction History) into separate components for better maintainability.

Example structure:

// components/subscription/CurrentPlanSection.tsx
export function CurrentPlanSection({ plan, onChangePlan }) { ... }

// components/subscription/ProBenefitsSection.tsx
export function ProBenefitsSection({ benefits }) { ... }

// components/subscription/PaymentMethodSection.tsx
export function PaymentMethodSection({ card, onUpdatePayment }) { ... }

// components/subscription/TransactionHistorySection.tsx
export function TransactionHistorySection({ subscriptionData, userSlug }) { ... }

This would improve code organization, reusability, and testability.

apps/masterbots.ai/components/routes/preferences/preference-section.tsx (2)

168-202: Consider improving type safety and error handling.

The function works well but could be enhanced for better type safety and robustness.

Consider this more type-safe implementation:

+const SWITCH_NAME_MAP = {
+  'deep-expertise': 'deepExpertise',
+  'web-search': 'webSearch'
+} as const;
+
+type SwitchName = keyof typeof SWITCH_NAME_MAP;
+
 const checkSwitchChange = async ({
 	switchName,
 	checked,
 }: {
-	switchName: 'deep-expertise' | 'web-search'
+	switchName: SwitchName
 	checked: boolean
 }) => {
 	const toggleModeOptions: PreferenceSetInput = {}
 
-	switch (switchName) {
-		case 'deep-expertise':
-			toggleModeOptions.deepExpertise = checked
-			break
-		case 'web-search':
-			toggleModeOptions.webSearch = checked
-			break
-		default:
-			break
-	}
+	const preferenceKey = SWITCH_NAME_MAP[switchName];
+	if (!preferenceKey) {
+		console.error(`Unknown switch name: ${switchName}`);
+		return;
+	}
+	
+	toggleModeOptions[preferenceKey as keyof PreferenceSetInput] = checked;

This approach:

  • Centralizes the mapping between UI names and preference keys
  • Provides better type safety
  • Makes it easier to add new preferences

259-268: Improve type safety for switch name casting.

The current type assertion could lead to runtime errors if item.props?.switchName doesn't match the expected types.

Consider adding a type guard:

+const isValidSwitchName = (name: unknown): name is ('deep-expertise' | 'web-search') => {
+  return name === 'deep-expertise' || name === 'web-search';
+};
+
 onCheckedChange={(checked) =>
-	checkSwitchChange({
-		checked,
-		switchName: item.props?.switchName as
-			| 'deep-expertise'
-			| 'web-search',
-	})
+	item.props?.switchName && isValidSwitchName(item.props.switchName) &&
+	checkSwitchChange({
+		checked,
+		switchName: item.props.switchName,
+	})
 }
packages/mb-drizzle/src/drizzle/0000_pink_lionheart.sql (1)

1-3: Clarify migration execution instructions.

The comment indicates this migration needs to be uncommented before execution. Consider adding clearer instructions about when and how this should be executed, especially since this appears to be an initial schema creation.

packages/mb-drizzle/src/drizzle/schema.ts (2)

104-104: Remove redundant unique constraint on primary key

The promptId is already defined as a primary key, which inherently enforces uniqueness. This additional unique constraint is redundant.

-		unique('prompt_prompt_id_key').on(table.promptId),

681-686: Simplify redundant primary key structure

Similar to the thread table, the composite primary key on (messageId, slug) is redundant when messageId already has a unique constraint.

-		primaryKey({
-			columns: [table.messageId, table.slug],
-			name: 'message_pkey',
-		}),
 		unique('message_id_key').on(table.messageId),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51387d0 and e0a8238.

⛔ Files ignored due to path filters (4)
  • bun.lock is excluded by !**/*.lock
  • packages/mb-genql/generated/schema.graphql is excluded by !**/generated/**
  • packages/mb-genql/generated/schema.ts is excluded by !**/generated/**
  • packages/mb-genql/generated/types.ts is excluded by !**/generated/**
📒 Files selected for processing (54)
  • apps/hasura/metadata/databases/masterbots/tables/public_preference.yaml (1 hunks)
  • apps/hasura/metadata/databases/masterbots/tables/public_user.yaml (3 hunks)
  • apps/hasura/migrations/masterbots/1718416395664_create_table_models_enum/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1745471202166_create_table_public_models/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1747220015500_alter_table_public_preference_add_column_web_search/down.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1747220015500_alter_table_public_preference_add_column_web_search/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1747220030651_alter_table_public_preference_add_column_deep_expertise/down.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1747220030651_alter_table_public_preference_add_column_deep_expertise/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748042391832_alter_table_public_preference_alter_column_user_id/down.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748042391832_alter_table_public_preference_alter_column_user_id/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748071543571_alter_table_public_preference_alter_column_chatbot_id/down.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748071543571_alter_table_public_preference_alter_column_chatbot_id/up.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748071970273_alter_table_public_preference_alter_column_chatbot_id/down.sql (1 hunks)
  • apps/hasura/migrations/masterbots/1748071970273_alter_table_public_preference_alter_column_chatbot_id/up.sql (1 hunks)
  • apps/hasura/seeds/masterbots/1724270512560_init_users_seeds.sql (1 hunks)
  • apps/masterbots.ai/app/actions/ai-executers.ts (1 hunks)
  • apps/masterbots.ai/app/actions/ai-main-call.ts (6 hunks)
  • apps/masterbots.ai/app/api/auth/signup/route.ts (2 hunks)
  • apps/masterbots.ai/app/api/chat/models/models.ts (1 hunks)
  • apps/masterbots.ai/app/u/[userSlug]/layout.tsx (1 hunks)
  • apps/masterbots.ai/auth.ts (4 hunks)
  • apps/masterbots.ai/components/routes/chat/chat-message.tsx (3 hunks)
  • apps/masterbots.ai/components/routes/chat/chat-options.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/chat/share-button.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/preferences/preference-section.tsx (5 hunks)
  • apps/masterbots.ai/components/routes/preferences/preferences.tsx (1 hunks)
  • apps/masterbots.ai/components/routes/profile/empty-state.tsx (1 hunks)
  • apps/masterbots.ai/components/routes/profile/user-card.tsx (2 hunks)
  • apps/masterbots.ai/components/routes/subscription/subscription-page.tsx (1 hunks)
  • apps/masterbots.ai/components/routes/thread/user-thread-panel.tsx (2 hunks)
  • apps/masterbots.ai/components/shared/generated-image.tsx (2 hunks)
  • apps/masterbots.ai/lib/constants/domain-slugs.ts (1 hunks)
  • apps/masterbots.ai/lib/constants/preferences.ts (2 hunks)
  • apps/masterbots.ai/lib/constants/prompts.ts (1 hunks)
  • apps/masterbots.ai/lib/helpers/ai-helpers.ts (2 hunks)
  • apps/masterbots.ai/lib/helpers/ai-schemas.ts (2 hunks)
  • apps/masterbots.ai/lib/hooks/use-mb-chat.tsx (2 hunks)
  • apps/masterbots.ai/lib/hooks/use-thread.tsx (3 hunks)
  • apps/masterbots.ai/services/admin/admin.service.ts (3 hunks)
  • apps/masterbots.ai/services/hasura/hasura.service.ts (3 hunks)
  • apps/masterbots.ai/types/types.ts (7 hunks)
  • packages/mb-drizzle/drizzle.config.ts (1 hunks)
  • packages/mb-drizzle/drizzle/0001_round_malcolm_colcord.sql (0 hunks)
  • packages/mb-drizzle/drizzle/meta/0001_snapshot.json (0 hunks)
  • packages/mb-drizzle/drizzle/meta/_journal.json (0 hunks)
  • packages/mb-drizzle/package.json (1 hunks)
  • packages/mb-drizzle/src/drizzle/0000_pink_lionheart.sql (1 hunks)
  • packages/mb-drizzle/src/drizzle/meta/0000_snapshot.json (1 hunks)
  • packages/mb-drizzle/src/drizzle/meta/_journal.json (1 hunks)
  • packages/mb-drizzle/src/drizzle/relations.ts (1 hunks)
  • packages/mb-drizzle/src/drizzle/schema.ts (1 hunks)
  • packages/mb-drizzle/src/index.ts (1 hunks)
  • packages/mb-drizzle/src/schema/auth.ts (0 hunks)
  • packages/mb-drizzle/src/schema/index.ts (0 hunks)
💤 Files with no reviewable changes (5)
  • packages/mb-drizzle/src/schema/index.ts
  • packages/mb-drizzle/drizzle/0001_round_malcolm_colcord.sql
  • packages/mb-drizzle/src/schema/auth.ts
  • packages/mb-drizzle/drizzle/meta/0001_snapshot.json
  • packages/mb-drizzle/drizzle/meta/_journal.json
🧰 Additional context used
🧠 Learnings (1)
apps/masterbots.ai/components/routes/chat/share-button.tsx (1)
Learnt from: AndlerRL
PR: bitcashorg/masterbots#287
File: apps/masterbots.ai/components/routes/chat/share-button.tsx:10-29
Timestamp: 2024-10-23T00:00:06.253Z
Learning: When implementing the `handleShare` function in `apps/masterbots.ai/components/routes/chat/share-button.tsx`, prefer using modern APIs like the Clipboard API over deprecated methods like `document.execCommand('copy')`, as the project no longer needs to support very old web browsers.
🧬 Code Graph Analysis (11)
packages/mb-drizzle/drizzle.config.ts (1)
packages/mb-env/src/config.env.ts (1)
  • appConfig (2-51)
packages/mb-drizzle/src/index.ts (1)
packages/mb-env/src/config.env.ts (1)
  • appConfig (2-51)
apps/masterbots.ai/app/api/auth/signup/route.ts (1)
apps/masterbots.ai/services/admin/admin.service.ts (1)
  • insertAdminUserPreferences (107-119)
apps/masterbots.ai/components/routes/thread/user-thread-panel.tsx (2)
apps/masterbots.ai/components/routes/profile/empty-state.tsx (1)
  • EmptyState (3-22)
apps/masterbots.ai/components/routes/chat/chat-chatbot-details.tsx (1)
  • ChatChatbotDetails (12-126)
apps/masterbots.ai/components/routes/chat/chat-message.tsx (3)
apps/masterbots.ai/lib/helpers/ai-helpers.ts (2)
  • hasImageGeneration (316-324)
  • extractImageContent (326-356)
apps/masterbots.ai/types/types.ts (1)
  • MessageWithExamples (429-431)
apps/masterbots.ai/components/shared/generated-image.tsx (1)
  • GeneratedImage (12-91)
apps/masterbots.ai/app/actions/ai-main-call.ts (2)
apps/masterbots.ai/types/types.ts (1)
  • StreamTextParams (222-222)
apps/masterbots.ai/lib/helpers/ai-schemas.ts (1)
  • webSearch (5-12)
apps/masterbots.ai/components/routes/preferences/preference-section.tsx (6)
packages/mb-genql/generated/schema.ts (1)
  • PreferenceSetInput (7258-7269)
apps/masterbots.ai/auth.ts (1)
  • session (174-189)
apps/masterbots.ai/services/hasura/hasura.service.ts (1)
  • updatePreferences (1874-1916)
apps/masterbots.ai/components/ui/card.tsx (1)
  • CardContent (79-79)
apps/masterbots.ai/components/ui/toggle-group.tsx (1)
  • ToggleGroup (61-61)
apps/masterbots.ai/components/ui/button.tsx (1)
  • Button (71-71)
apps/masterbots.ai/lib/helpers/ai-helpers.ts (2)
packages/mb-drizzle/src/drizzle/schema.ts (1)
  • message (639-689)
apps/masterbots.ai/types/types.ts (2)
  • MessageWithExamples (429-431)
  • StoredImagePart (423-427)
apps/masterbots.ai/services/hasura/hasura.service.ts (2)
packages/mb-genql/generated/schema.ts (2)
  • PreferenceSetInput (7258-7269)
  • PreferenceInsertInput (7141-7158)
packages/mb-lib/src/hasura/hasura.lib.ts (1)
  • getHasuraClient (19-54)
apps/masterbots.ai/services/admin/admin.service.ts (2)
packages/mb-drizzle/src/index.ts (1)
  • db (10-10)
packages/mb-drizzle/src/drizzle/schema.ts (2)
  • user (214-256)
  • preference (132-189)
packages/mb-drizzle/src/drizzle/relations.ts (1)
packages/mb-drizzle/src/drizzle/schema.ts (28)
  • chatbot (38-82)
  • complexityEnum (112-115)
  • lengthEnum (117-120)
  • toneEnum (122-125)
  • typeEnum (127-130)
  • preference (132-189)
  • socialFollowing (336-378)
  • chatbotCategory (398-424)
  • promptChatbot (426-452)
  • chatbotDomain (510-536)
  • thread (587-637)
  • prompt (88-106)
  • promptTypeEnum (108-110)
  • promptUser (454-480)
  • user (214-256)
  • referral (191-212)
  • userToken (482-508)
  • example (273-301)
  • subcategoryEnum (562-585)
  • categoryEnum (538-560)
  • tagEnum (316-334)
  • domainEnum (303-306)
  • models (380-396)
  • modelsEnum (258-271)
  • category (29-36)
  • token (308-314)
  • message (639-689)
  • messageTypeEnum (84-86)
🔇 Additional comments (63)
apps/hasura/migrations/masterbots/1748042391832_alter_table_public_preference_alter_column_user_id/up.sql (1)

1-1: Migration Reversibility: Confirm down migration exists.
Verify that a corresponding down.sql is implemented to drop the preference_user_id_key constraint, making this change reversible.

apps/masterbots.ai/app/u/[userSlug]/layout.tsx (1)

28-28: No-op Change: Class order reorder is harmless.
The CSS class sequence was reordered but the applied styles remain identical.

apps/hasura/migrations/masterbots/1748071970273_alter_table_public_preference_alter_column_chatbot_id/up.sql (1)

1-1: Migration Reversibility: Add a down migration to drop the default.
Ensure there is a down.sql counterpart that removes the default value for chatbot_id to maintain reversible migrations.

packages/mb-drizzle/src/index.ts (1)

4-4: LGTM! Schema reorganization looks clean.

The import and export path changes properly reflect the restructuring from ./schema to ./drizzle/schema and the addition of relations export improves the separation of concerns between schema definitions and ORM relations.

Also applies to: 12-13

apps/hasura/seeds/masterbots/1724270512560_init_users_seeds.sql (1)

2-3: Note: Cannot review actual seed data changes.

This file shows only Git LFS pointer metadata changes (updated SHA256 hash and file size). The actual SQL seed data content is stored in Git LFS and not visible for review.

To ensure the seed data changes align with the preference schema updates mentioned in the AI summary, please verify that the actual seed file content properly initializes the new web_search and deep_expertise preference columns.

packages/mb-drizzle/package.json (1)

8-8: Verify script change compatibility.

The generate script was simplified by removing the :pg target. Ensure this works correctly with the upgraded drizzle-kit version.

apps/hasura/migrations/masterbots/1745471202166_create_table_public_models/up.sql (1)

30-33: LGTM! Image generation models added correctly.

The addition of image generation models (Gemini 2.0 Flash Exp, GPT Image 1, DALL-E 2/3) aligns well with the PR's objective to extend image generation support. The migration follows best practices with proper conflict handling.

apps/masterbots.ai/lib/helpers/ai-schemas.ts (2)

1-1: Import cleanup looks good.

Removing the unused getWebSearchTool import is appropriate since the webSearch tool is now commented out.


15-28: Good approach to preserve the old web search implementation.

Commenting out the webSearch tool definition rather than deleting it maintains code history and allows for easy rollback if needed. This is a prudent approach during the transition to the new OpenAI web search preview tool.

packages/mb-drizzle/drizzle.config.ts (2)

6-9: Configuration modernization looks good.

The changes align with modern Drizzle-kit practices:

  • Moving output to ./src/drizzle follows convention
  • Using dialect: 'postgresql' instead of driver setting
  • Renaming connectionString to url matches current API

5-5:

Details

❓ Verification inconclusive

Verify schema discovery works without explicit schema path.

Commenting out the schema path suggests reliance on automatic schema discovery. Ensure this works correctly with your current setup.


🏁 Script executed:

#!/bin/bash
# Description: Check if schema files exist in the expected location for auto-discovery
# Expected: Schema files should be discoverable

fd -e ts -e js "schema" packages/mb-drizzle/src/

Length of output: 90


Confirm Drizzle Schema Auto-Discovery
We located your generated schema file at packages/mb-drizzle/src/drizzle/schema.ts. Commenting out the old schema path is safe only if Drizzle CLI will pick up this new location automatically.

• Run your migration/generation command (e.g. npx drizzle-kit generate) to ensure there are no “schema not found” errors.
• If Drizzle cannot discover your definitions, re-enable or update the schema field in packages/mb-drizzle/drizzle.config.ts:

- // schema: './src/schema/*',
+ schema: './src/drizzle/*.ts',
apps/masterbots.ai/components/routes/profile/user-card.tsx (1)

18-18: LGTM: Import addition is correct.

The BadgeCheck import from lucide-react is properly added to support the pro badge feature.

packages/mb-drizzle/src/drizzle/meta/_journal.json (1)

1-13:

Details

✅ Verification successful

Validate migration timestamp and verify journal integrity.

The Drizzle migration journal structure is correct, but there's a timestamp concern:

  1. Future timestamp: The timestamp 1748048353525 (≈ Jan 2025) appears to be in the future, which might indicate this was generated in a development/testing environment
  2. Fresh journal: This appears to be a new journal starting at version 7, which suggests a schema reset or major migration

🏁 Script executed:

#!/bin/bash
# Description: Check if this timestamp makes sense in context and verify related migration files
# Expected: Find corresponding migration files and validate the journal state

# Check for the corresponding migration file
fd "0000_pink_lionheart" --type f

# Look for any other journal or snapshot files that might provide context
fd "_journal.json|snapshot.json" --type f

# Convert timestamp to human readable date for verification
python3 -c "import datetime; print(datetime.datetime.fromtimestamp(1748048353525/1000).strftime('%Y-%m-%d %H:%M:%S'))"

Length of output: 387


Confirm migration journal integrity

  • Migration file packages/mb-drizzle/src/drizzle/0000_pink_lionheart.sql and snapshot packages/mb-drizzle/src/drizzle/meta/0000_snapshot.json are present.
  • The timestamp 1748048353525 converts to 2025-05-24 00:59:13, which aligns with the expected migration execution window.
  • Journal structure in packages/mb-drizzle/src/drizzle/meta/_journal.json follows Drizzle conventions and requires no changes.
apps/masterbots.ai/lib/constants/prompts.ts (1)

207-208: LGTM! Excellent enhancements to AI assistant behavior.

These additions significantly improve the AI assistant's capabilities:

  1. Web search integration: The instruction to use web_search_preview tool for recent information aligns perfectly with the new web search preferences and infrastructure added in this PR.

  2. Better user guidance: Directing users to find other Masterbots for questions outside the current bot's expertise improves the overall platform experience and specialization.

Both instructions are well-integrated into the existing prompt structure and support the broader user preference management system introduced in this PR.

apps/masterbots.ai/components/routes/profile/empty-state.tsx (2)

3-6: LGTM! Great enhancement to component flexibility.

Adding optional title and description props with sensible defaults makes this component much more reusable while maintaining backward compatibility.


10-19: LGTM! Excellent dark mode support implementation.

The dark mode styling is properly implemented across all visual elements:

  • Icon: text-gray-400 dark:text-white
  • Heading: text-gray-800 dark:text-white
  • Description: text-gray-600 dark:text-gray-100

This ensures consistent visual hierarchy and accessibility across both light and dark themes.

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

56-56: LGTM! Proper import for enhanced EmptyState component.

The import correctly references the newly enhanced EmptyState component that now supports customizable props.


421-428: LGTM! Excellent UX improvement for profile pages.

This conditional rendering provides much better user experience:

  • Profile context: Shows specific empty state with user-relevant messaging when viewing profiles with no threads
  • Maintained functionality: Falls back to ChatChatbotDetails for non-profile pages, preserving existing behavior
  • Clear messaging: The customized title and description clearly communicate the empty state to users

The logic is clean and the integration with the enhanced EmptyState component is well-executed.

apps/masterbots.ai/lib/hooks/use-thread.tsx (4)

5-5: LGTM! Necessary import for user preference fetching.

Adding getUserBySlug import supports the new async user data fetching functionality that synchronizes user preferences with the frontend state.


10-10: LGTM! Proper import for async operations.

The useAsync import is correctly added to support the asynchronous fetching of user preferences.


51-67: LGTM! Well-implemented async user preference synchronization.

This implementation excellently handles user preference fetching:

  • Proper dependency: Uses session?.user.slug as dependency to trigger fetch when user session is available
  • State synchronization: Updates webSearch state from stored user preferences, ensuring frontend-backend consistency
  • Clean async handling: Uses useAsync hook appropriately with proper error and loading state management
  • Defensive coding: Safely handles undefined session and user data with optional chaining

This aligns perfectly with the broader user preference management system introduced in this PR, including the new database schema and backend services.


97-97: LGTM! Dynamic initialization of webSearch state.

Initializing webSearch from userData?.preferences[0].webSearch ?? false ensures the state reflects the user's actual stored preferences rather than a static default. The fallback to false provides safe handling when user data is not yet available.

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

27-31: Excellent UX enhancement with tooltip feedback!

The tooltip integration provides clear user feedback without disrupting the existing functionality. The conditional display logic (open={status !== 'default' && status !== 'loading'}) ensures the tooltip only appears when relevant, and the contextual messages effectively communicate the operation status to users.

Also applies to: 79-108

apps/hasura/metadata/databases/masterbots/tables/public_user.yaml (2)

4-11: Proper object relationship definition for user preferences.

The new preference relationship correctly establishes the foreign key constraint on user_id, enabling seamless access to user preference data through GraphQL queries.


175-175: Appropriate permission extension for deletion request functionality.

Adding deletion_requested_at to update permissions for both moderator and user roles properly supports the user deletion workflow while maintaining role-based access control.

Also applies to: 195-195

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

133-140: Improved conditional logic for pending approval display.

The refined condition !thread.isApproved && thread.isPublic correctly shows the pending approval status only when the thread is public but awaiting approval, eliminating unnecessary UI clutter.


179-187: Enhanced share button availability logic.

The condition thread?.isApproved && thread?.isPublic ensures the share option is only available when the thread is actually shareable, providing a cleaner and more intuitive user experience by removing the previous disabled state approach.

apps/masterbots.ai/app/api/auth/signup/route.ts (2)

7-7: LGTM: Proper import for preference service

The import statement correctly references the admin service function for inserting user preferences.


110-128: Excellent implementation of preference initialization with robust error handling

This addition ensures that user preferences are consistently initialized during signup, which is critical for the user experience. The implementation includes:

  • Proper default preference values that align with the database schema
  • Robust error handling that aborts the signup process if preference creation fails
  • Clear error messaging for debugging

The default values (webSearch: false, deepExpertise: false, etc.) are appropriate defaults that align with the new preference columns mentioned in the database migrations.

apps/masterbots.ai/lib/constants/preferences.ts (1)

17-20: Well-structured UI mapping properties for preference controls

The addition of props objects with switchId and switchName provides excellent consistency between frontend controls and backend preference management. The naming convention is clear and aligns with the preference keys used in the database schema:

  • theme and font-size for general preferences
  • web-search and deep-expertise for thread preferences matching the new database columns

This standardization will improve maintainability and reduce mapping errors between UI and backend.

Also applies to: 27-30, 42-45, 52-55

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

436-437: Consistent use of examples filtering for file parts

The change to filter finalMessage.parts for type === 'file' and assign to the examples property is consistent with the broader refactoring. This maintains the same filtering logic while using the new property structure.

apps/masterbots.ai/lib/constants/domain-slugs.ts (1)

104-166: Comprehensive expansion of domain categories with consistent naming

The addition of 63 new domain slugs significantly expands the available categorization options. The new entries:

  • Follow consistent kebab-case naming convention
  • Cover diverse and relevant topic areas (food systems, gaming, AI/ML, finance, productivity, etc.)
  • Use descriptive, compound names that clearly indicate the domain focus
  • Appear to be non-duplicative and well-organized

This expansion will provide better granularity for domain categorization and user preference management.

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

113-142: Good use of memoization for ImagesSection.

The refactoring to use useMemo is a good performance optimization that prevents unnecessary re-renders of the images section. The dependency array correctly includes only the message prop.


130-130: Excellent improvement to image key generation.

Using a combination of message ID and a substring of the base64 content creates stable, unique keys that persist across re-renders. This is much better than using array indices.

apps/masterbots.ai/auth.ts (1)

211-212: Good approach for unique slug generation.

Adding a timestamp to the slug ensures uniqueness even for users with identical names. This prevents potential conflicts.

apps/masterbots.ai/components/shared/generated-image.tsx (3)

20-26: Excellent state management with useEffect.

The useEffect hook properly resets both loading and error states when the base64 prop changes, ensuring a clean state for each new image.


30-32: Smart handling of base64 data formats.

The conditional check for data URL prefix ensures the component works with both raw base64 strings and complete data URLs.


47-88: Well-designed UI with comprehensive states.

The component handles all states gracefully:

  • Error display with clear messaging
  • Loading indicator with spinner
  • Conditional download button that only appears when the image is ready
  • Smooth transitions and hover effects

The use of unoptimized and priority props on the Next.js Image component is appropriate for AI-generated images.

apps/masterbots.ai/app/actions/ai-main-call.ts (2)

336-339: Good integration of web search tool.

The conditional activation of the web search preview tool based on the webSearch flag properly integrates with user preferences.


457-464: Appropriate model-specific handling for Gemini.

The special handling for Gemini 2.0 Flash Exp model to use only user messages is a necessary adaptation for this specific model's requirements.

apps/masterbots.ai/services/hasura/hasura.service.ts (3)

1346-1349: LGTM! Proper integration of user preferences.

The addition of the preferences field to the getUserBySlug query is well-placed and follows the established pattern of using __scalar: true to fetch all scalar fields.


1873-1916: Well-implemented preference update function.

The updatePreferences function follows established patterns with proper error handling and authentication requirements. The implementation correctly updates preferences based on userId.


1918-1953:

Details

✅ Verification successful

Verify userId is included in the preference insert.

The insertPreferencesByUserId function is well-structured, but the function name suggests it should insert preferences for a specific userId. However, the implementation doesn't explicitly ensure that userId is included in the preferencesSet object.

Consider either:

  1. Explicitly setting the userId in the object before insertion
  2. Renaming the function to better reflect that userId should be included in preferencesSet

🏁 Script executed:

#!/bin/bash
# Check how insertPreferencesByUserId is used to verify if userId is always passed in preferencesSet
rg -A 10 "insertPreferencesByUserId" --type ts

Length of output: 2244


insertPreferencesByUserId usage verified – no changes needed

I checked all call sites of insertPreferencesByUserId (e.g. in apps/masterbots.ai/auth.ts) and confirmed that every invocation passes a preferencesSet object containing userId. Since the function already relies on the caller to include userId, no additional enforcement or renaming is required.

apps/masterbots.ai/services/admin/admin.service.ts (2)

34-36: Excellent type safety improvement!

Using Partial<typeof user.$inferSelect> is the correct Drizzle pattern for typing partial updates, providing better type safety and IntelliSense support.


98-100: Good type safety enhancement for role parameter.

Explicitly typing the role parameter as a union of valid role values prevents invalid roles from being passed and improves type safety.

apps/masterbots.ai/components/routes/preferences/preference-section.tsx (2)

144-166: Well-implemented async preference update handler.

The toggleMode function properly validates the session, handles errors gracefully, and provides user feedback through toast notifications. Good use of useAsyncFn for async state management.


275-276: UI elements intentionally disabled.

The ToggleGroup and Plus button are now disabled with appropriate visual feedback (opacity and cursor changes). This appears to be an intentional design decision to restrict these features.

Also applies to: 299-299

apps/masterbots.ai/types/types.ts (6)

3-4: LGTM! Import updates align with schema migration.

The import changes correctly reflect the migration to the new Drizzle ORM schema and the integration of AI SDK functionality.


126-126: Good addition for subscription period tracking.

The current_period_end field addition to both the Subscription type and initialStateSubscription provides necessary data for subscription management UI and billing logic.

Also applies to: 145-145


222-222: Clean use of utility type for AI SDK integration.

Using Parameters<typeof streamText>[0] ensures type safety and maintains compatibility with the AI SDK's streamText function signature changes.


423-431: Well-structured types for image handling enhancement.

The new StoredImagePart and MessageWithExamples types provide a clean interface for storing and handling AI-generated images. The type definitions are comprehensive and follow good TypeScript practices.


316-316:

Details

❓ Verification inconclusive

Verify the role narrowing doesn't break existing functionality.

The AdminUserUpdate.role field was changed from a dynamic union based on UserRole to a static literal union. This strengthens type safety but could break existing code that relies on the previous dynamic typing.


🏁 Script executed:

#!/bin/bash
# Search for AdminUserUpdate usage to verify compatibility with the new role type
rg -A 5 -B 2 "AdminUserUpdate" --type ts

Length of output: 523


🏁 Script executed:

#!/bin/bash
# Search for AdminUserUpdate usage in the codebase excluding its own definition
rg -n "AdminUserUpdate" --type ts | grep -v "types.ts"

Length of output: 52


🏁 Script executed:

#!/bin/bash
# Retrieve the definition of UserRole to compare against the static union in AdminUserUpdate
rg -A5 -B2 "export type UserRole" --type ts

Length of output: 45


Confirm AdminUserUpdate.role change and coverage of all role values

I didn’t find any references to AdminUserUpdate outside its definition (apps/masterbots.ai/types/types.ts:316), nor could I locate the original UserRole type to compare. Please verify:

• That no code (resolvers, services, controllers, UI forms, etc.) still relies on a broader or different set of UserRole values.
• That the static union ‘admin’ | ‘user’ | ‘moderator’ | ‘anonymous’ matches every role used at runtime (database enums, API contracts, front-end).
• That there are no lingering imports or generated types expecting a dynamic UserRole alias.

If everything aligns, the narrowed literal union is safe and will improve type safety.


389-389:

Details

✅ Verification successful

Preference props narrowing may break existing code.

The PreferenceItemType.props field was narrowed from Record<string, any> to Record<string, string>. This change requires all prop values to be strings, which could break existing code that uses non-string values.


🏁 Script executed:

#!/bin/bash
# Search for PreferenceItemType usage and props assignments to check for potential breaking changes
rg -A 10 -B 2 "PreferenceItemType|props.*:" --type ts

Length of output: 103938


🏁 Script executed:

#!/bin/bash
# Search for import or usage of 'preferences' constant in TSX files
rg -n "import.*preferences" -t tsx

Length of output: 64


🏁 Script executed:

#!/bin/bash
# Search for imports of the preferences constant in TSX files
rg -n "import.*preferences" -g '*.tsx'

Length of output: 293


🏁 Script executed:

#!/bin/bash
# Display the Preferences component implementation to see how props are used
sed -n '1,200p' apps/masterbots.ai/components/routes/preferences/preferences.tsx

# Show the page where Preferences component is used to inspect passed props
sed -n '1,200p' apps/masterbots.ai/app/u/[userSlug]/s/pref/page.tsx

Length of output: 974


🏁 Script executed:

#!/bin/bash
# Display PreferenceSection component implementation
sed -n '1,200p' apps/masterbots.ai/components/routes/preferences/preference-section.tsx

Length of output: 5183


🏁 Script executed:

#!/bin/bash
# Show PreferenceItem component implementation
sed -n '1,200p' apps/masterbots.ai/components/routes/preferences/preference-item.tsx

Length of output: 399


🏁 Script executed:

#!/bin/bash
# Show how props is used within PreferenceSection component
grep -R "props" -n apps/masterbots.ai/components/routes/preferences/preference-section.tsx

Length of output: 234


Props narrowing is safe – no non-string values found
All existing props assignments in lib/constants/preferences.ts are string literals, and PreferenceSection only uses them for string id/name attributes. No code passes non-string values to props, so changing to Record<string, string> won’t break anything.

apps/hasura/metadata/databases/masterbots/tables/public_preference.yaml (2)

50-78: Good addition of new preference fields to select permissions.

The deep_expertise and web_search fields are correctly added to both moderator and user select permissions, maintaining consistency with the table schema changes.


79-107: Proper user ownership enforcement in update permissions.

The update permissions correctly enforce user ownership through the user_id filter for the user role, while allowing moderators unrestricted updates. The addition of new preference fields is consistent.

packages/mb-drizzle/src/drizzle/0000_pink_lionheart.sql (3)

70-72: Good default values for new preference fields.

The web_search and deep_expertise boolean fields are properly defined with DEFAULT false, ensuring backward compatibility and safe defaults for existing data.


144-144: Excellent self-referencing constraint.

The check constraint CHECK (follower_id <> followee_id) properly prevents users from following themselves, which is a good business logic enforcement at the database level.


276-279: Performance-optimized indexes.

The indexes on user.role, models_enum.value, and social following relationships are well-placed for query optimization. The use of specific operator classes (enum_ops, text_ops, uuid_ops) shows attention to PostgreSQL performance best practices.

packages/mb-drizzle/src/drizzle/relations.ts (4)

33-56: Comprehensive chatbot relationship mappings.

The chatbot relations correctly map all foreign key relationships to enum tables and establish proper many-to-one and one-to-many relationships. The relationship structure aligns well with the schema definitions.


97-122: Well-structured preference relations.

The preference relations properly map all foreign key constraints to their respective tables and enums. The relationships correctly reflect the schema design where preferences link users to chatbots with specific enum values.


124-141: Proper handling of complex user relationships.

The user relations correctly handle multiple self-referential relationships (referrals, social following) using distinct relation names to avoid conflicts. This is essential for proper ORM functionality with complex many-to-many relationships.


309-318: Self-referential thread relationship correctly implemented.

The parent-child thread relationship uses proper relation naming (thread_parentThreadId_thread_threadId) to distinguish between the parent and child sides of the relationship, which is crucial for avoiding ORM confusion.

packages/mb-drizzle/src/drizzle/schema.ts (1)

1-19: LGTM!

All necessary Drizzle ORM imports are properly included.

@@ -0,0 +1 @@
alter table "public"."preference" add constraint "preference_user_id_key" unique ("user_id");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Precondition Check: Ensure no duplicate user_id entries exist.
Applying a unique constraint will fail if there are duplicate user_id values. Introduce a pre-migration step to identify or remove duplicates before enforcing uniqueness.

🤖 Prompt for AI Agents
In
apps/hasura/migrations/masterbots/1748042391832_alter_table_public_preference_alter_column_user_id/up.sql
at line 1, before adding the unique constraint on "user_id", add a pre-migration
step to check for duplicate "user_id" entries. This can be done by querying the
table for duplicates and either removing or handling them appropriately to
ensure the unique constraint can be applied without errors.

@@ -0,0 +1 @@
alter table "public"."preference" alter column "chatbot_id" set not null;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Data Integrity: Ensure no NULL chatbot_id values before reverting.
Enforcing NOT NULL will fail if any rows currently have chatbot_id set to NULL. Add a cleanup or backfill step to set appropriate non-null values before applying this down migration.

🤖 Prompt for AI Agents
In
apps/hasura/migrations/masterbots/1748071543571_alter_table_public_preference_alter_column_chatbot_id/down.sql
at line 1, before setting the "chatbot_id" column to NOT NULL, add a step to
update or backfill any existing NULL values in this column to valid non-null
values to prevent migration failure. This ensures data integrity by avoiding NOT
NULL constraint violations during the migration.

"dependencies": {
"drizzle-orm": "^0.29.3",
"pg": "^8.11.3",
"drizzle-orm": "^0.43.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify compatibility with major version upgrades.

The drizzle-orm upgrade from ^0.29.3 to ^0.43.1 and drizzle-kit upgrade from ^0.20.14 to ^0.31.1 are major version jumps that may introduce breaking changes.

Please verify that:

  1. The new drizzle-orm version is compatible with the existing schema definitions
  2. The new drizzle-kit version supports the current migration and generation workflows
  3. No breaking changes affect the existing database operations

Also applies to: 19-19


🌐 Web query:

What are the breaking changes between drizzle-orm 0.29.3 and 0.43.1?

💡 Result:

Breaking Changes Between drizzle-orm 0.29.3 and 0.43.1

Moving from drizzle-orm 0.29.3 to 0.43.1 involves several releases, each introducing new features, improvements, and important breaking changes. Here are the key breaking changes and major updates you should be aware of:

Minimum Required Versions and Compatibility

  • Starting with v0.29.0, Drizzle ORM requires a minimum Drizzle Kit version of 0.20.0 for full compatibility. If you upgrade Drizzle ORM beyond this point, you must also upgrade Drizzle Kit. Incompatibility between these packages may cause issues, especially if your version is older than 0.28.0[1].

Changes in Query Builder Behavior

  • v0.29.0 introduced a new dynamic mode for query builders, enabling dynamic building of queries by allowing methods to be called multiple times. This is activated by calling .$dynamic() on a query builder[1].
  • Previously, calling a query builder method more than once was restricted, which made it challenging to build queries dynamically.

Read Replica Support

  • Starting with v0.29.0, Drizzle ORM added support for read replicas using the withReplica function. This allows you to specify different database connections for read and write operations, offering more advanced load balancing and failover strategies[1].

Driver and Type Changes

  • Numerous changes were made to how database drivers (especially for PostgreSQL, MySQL, and SQLite) handle data types such as bigint, decimal, numeric, and various binary types. Some previously permitted type mismatches are now fixed, which may break code that depended on implicit conversions or lenient handling[2][8].

Schema and Table Definition Enhancements

  • Introduction of the casing parameter for automatic mapping between database column names (often snake_case) and TypeScript field names (often camelCase), requiring changes to table schema definitions if you want to benefit from this mapping[7].
  • New custom schema support for enums in Postgres and improved support for naming primary and foreign keys[5].

Raw SQL Execution Updates

  • Executing raw SQL queries is now possible by passing a string directly to db.execute(), not just via sql template tags, which may subtly change query execution and validation in existing code[7].

Client Access and Raw API

  • You can now access the underlying driver client from the Drizzle ORM instance via db.$client, enabling advanced operations but also changing how you access low-level features[7].

Special Breaking Changes for Turso/LibSQL Users

  • For users of Turso and LibSQL, starting with v0.34.0, you must upgrade both your drizzle.config and the @libsql/client package to v0.10.0 or above to use the migrate function[7].

Removed and Changed APIs

  • The .fullJoin() method was removed from the MySQL API[2].
  • For GEL (a dialect), all columns now require explicit schema and table prefixes due to issues with ambiguous column names in subqueries[2].
  • Some outdated or duplicated exports and types have been removed, which may break imports or type checks in existing TypeScript code[2].

Migration and SQL Generation

  • The migration API and Drizzle Kit have seen changes, particularly in configuration and environment variable handling. Some migration commands or config patterns from pre-0.30 versions may no longer work as expected[1][5].

Summary Table of Major Breaking Changes

Area Change/Removal/Addition Version Introduced
Drizzle Kit Version Minimum v0.20.0 required with v0.29.0+ 0.29.0
Query Builder .dynamic() mode required for repeatable operations 0.29.0
Read Replica Support withReplica function for read/write separation 0.29.0
Turso/LibSQL Migrations Must use @libsql/client@0.10.0+ for migrations 0.34.0
Schema Casing Mapping casing param for auto-mapping (snake_case/camelCase) 0.34.0
Raw SQL Execution Can now execute raw strings, not just templates 0.34.0
Driver and Type Fixes More strict typing, binary handling, big numbers, etc. 0.41.0+
MySQL .fullJoin() Method removed 0.43.0
GEL Prefixing Columns require explicit schema/table prefix 0.43.0
Duplicated Exports Removed old duplicated APIs and exports 0.43.0

Migration Advice

  • Upgrade dependencies in lockstep. Always upgrade Drizzle Kit and any related drivers or packages alongside Drizzle ORM.
  • Review schema and queries. Check usages of table definitions, raw SQL, and any custom types.
  • Test migration scripts. Make sure your migrations and seeds still work, especially if using Turso or custom enum support.

For complete details and guidance on migrating large codebases, consult the official release notes and migration guides for each relevant version[1][2][7][5].


References:
[1] Drizzle ORM v0.29.0 release notes
[2] GitHub release notes up to v0.43.1
[5] Drizzle ORM latest releases page
[7] Breaking changes summary for v0.34.0

Citations:


🌐 Web query:

What are the breaking changes between drizzle-kit 0.20.14 and 0.31.1?

💡 Result:

Between drizzle-kit versions 0.20.14 and 0.31.1, several breaking changes have been introduced. Here's a summary of the key changes:

1. Snapshots Upgrade:
All PostgreSQL and SQLite-generated snapshots have been upgraded to version 6. Users are prompted to upgrade them by running drizzle-kit up. (newreleases.io)

2. Removal of :dialect from CLI Commands:
The :dialect suffix has been removed from drizzle-kit CLI commands. Commands like drizzle-kit generate and drizzle-kit push no longer require specifying the dialect. This parameter has been moved to the drizzle.config.ts file. (newreleases.io)

3. Updates to drizzle.config.ts:
The configuration file has undergone significant changes:

  • dialect is now mandatory, specifying the database type (e.g., mysql, postgresql, or sqlite).
  • driver has become optional, with specific drivers available for different configurations.
  • url unifies the previously existing connectionString and uri.
  • migrations introduces parameters to specify custom tables and schemas for migrations.

These changes require updates to existing drizzle.config.ts files. (newreleases.io)

4. MySQL Schemas/Databases No Longer Supported:
Drizzle Kit no longer handles schema changes for additional schemas or databases in your drizzle schema file. (newreleases.io)

5. Introduction of New Features:

  • Pull Relations: Drizzle now extracts foreign key information from the database to generate a relations object, which can be found in the out folder after introspection. (newreleases.io)
  • Custom Migration Names: Users can specify names for migrations using the --name <name> flag.
  • New migrate Command: A new command, drizzle-kit migrate, allows direct application of generated migrations to the database.

6. Changes in Migration File Structure:
The migration file structure has been updated. Previously, migration files were organized by date, but now they are organized with a meta folder containing snapshot files and individual migration files. (newreleases.io)

7. Support for New Database Features:

  • PostgreSQL Sequences and Identity Columns: Migrations now support PostgreSQL sequences and identity columns.
  • MySQL and SQLite Generated Columns: Support has been added for generated columns in MySQL and SQLite. (github.com)

8. CLI Enhancements:

  • --force Flag for drizzle-kit push: A new --force flag allows auto-acceptance of all data-loss statements during the push command.
  • Migration File Prefix Customization: Users can customize migration file prefixes to suit their migration tools. (github.com)

9. Dependency Updates:
The package @esbuild-kit/esm-loader, previously marked as deprecated, has been moved to devDependencies to eliminate installation warnings. (github.com)

These changes may require adjustments to existing projects to ensure compatibility with the latest version of drizzle-kit.

Citations:


Action Required: Validate Drizzle ORM & Kit Major Upgrades

You’ve upgraded from drizzle-orm ^0.29.3 → ^0.43.1 and drizzle-kit ^0.20.14 → ^0.31.1, which include multiple breaking changes. Before merging, please:

  • Upgrade in lockstep
    • Ensure drizzle-kit ≥ 0.20.0 alongside ORM ≥ 0.29.0
    • If using Turso/LibSQL, bump @libsql/client to ≥ 0.10.0

  • Update drizzle.config.ts
    • Add mandatory dialect field and consolidate connectionString/uri into url
    • Adjust optional driver, migrations tables/schemas

  • Refresh snapshots & migrations
    • Run drizzle-kit up to move PG/SQLite snapshots to v6
    • Verify new drizzle-kit migrate/generate/push (no :dialect flag) workflows
    • Test PostgreSQL sequences, identity columns, and MySQL/SQLite generated columns

  • Refactor removed/changed APIs
    • Remove or replace any .fullJoin() calls (MySQL)
    • Adopt .dynamic() mode for repeat query-builder calls
    • Migrate to db.execute(string) raw SQL API if needed
    • Fix any imports broken by removed types/exports
    • Add casing mappings if you rely on snake_case ↔ camelCase conversions

  • Thoroughly test all database operations
    • Schema definitions, queries, and migration scripts for type or driver-level changes (bigint, decimal, binary)
    • End-to-end tests to catch subtle behavior shifts

Please address or confirm each of the above before approving this PR.

🤖 Prompt for AI Agents
In packages/mb-drizzle/package.json at line 14, you upgraded drizzle-orm from
^0.29.3 to ^0.43.1 and drizzle-kit from ^0.20.14 to ^0.31.1, which include major
breaking changes. To fix this, verify compatibility by upgrading drizzle-kit in
lockstep with drizzle-orm, update drizzle.config.ts to include the mandatory
dialect field and unify connection strings into url, refresh snapshots by
running drizzle-kit up, adjust migration workflows to the new CLI commands
without :dialect flags, refactor code to remove deprecated APIs like
.fullJoin(), adopt .dynamic() mode for query builders, migrate raw SQL calls to
the new db.execute(string) API, fix imports broken by removed exports, add
casing mappings if needed, and thoroughly test all database operations and
migrations for any breaking changes or type issues before merging.

Comment on lines +339 to 344
<h2 className="flex items-center gap-2 text-xl font-semibold md:text-2xl">
@{userData?.username?.toLowerCase()}
{userData?.proUserSubscriptionId && (
<BadgeCheck className="size-5 text-[#BE17E8] dark:text-[#83E56A]" />
)}
</h2>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve accessibility and consider design consistency.

The pro badge implementation is functional but could benefit from accessibility enhancements:

  1. The badge lacks proper ARIA attributes for screen readers
  2. Consider using semantic HTML or proper labeling for the badge
  3. The color values appear to be hardcoded - consider using CSS variables for design system consistency
-						<h2 className="flex items-center gap-2 text-xl font-semibold md:text-2xl">
-							@{userData?.username?.toLowerCase()}
-							{userData?.proUserSubscriptionId && (
-								<BadgeCheck className="size-5 text-[#BE17E8] dark:text-[#83E56A]" />
-							)}
-						</h2>
+						<h2 className="flex items-center gap-2 text-xl font-semibold md:text-2xl">
+							@{userData?.username?.toLowerCase()}
+							{userData?.proUserSubscriptionId && (
+								<BadgeCheck 
+									className="size-5 text-[#BE17E8] dark:text-[#83E56A]" 
+									aria-label="Pro subscriber"
+									role="img"
+								/>
+							)}
+						</h2>
🤖 Prompt for AI Agents
In apps/masterbots.ai/components/routes/profile/user-card.tsx around lines 339
to 344, improve accessibility by adding appropriate ARIA attributes to the
BadgeCheck component, such as aria-label or role, to ensure screen readers can
identify the badge meaning. Replace the hardcoded color values with CSS
variables to maintain design system consistency. Also, consider wrapping the
badge in a semantic HTML element or adding proper labeling to clarify its
purpose.

Comment on lines +20 to +23
('Gemini__Flash__IMG','gemini-2.0-flash-exp'),
('OpenAI__IMG','gpt-image-1'),
('OpenAI__Dalle__2','dall-e-2'),
('OpenAI__Dalle__3','dall-e-3')
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify consistency with application enums and consider migration reversibility.

The migration adds new image generation models, which aligns with the PR objectives. However, there are a few considerations:

  1. Enum consistency: Ensure these changes are reflected in the corresponding application enums
  2. Migration reversibility: Consider creating a corresponding down.sql migration for rollback scenarios
  3. Model naming: The change from Gemini__2_0__Flash to Gemini__Flash__IMG suggests a semantic shift - verify this aligns with usage patterns

🏁 Script executed:

#!/bin/bash
# Description: Verify consistency between database enum and application enum definitions
# Expected: Application enum should contain corresponding entries for the new models

# Search for AIModels enum and related model definitions
rg -A 20 "enum.*Models|Models.*enum" --type ts

# Search for usage of the new model names in the codebase
rg "gpt-image-1|dall-e-2|dall-e-3|gemini-2.0-flash-exp" --type ts

Length of output: 7523


🏁 Script executed:

#!/bin/bash
set -e
MIG_DIR="apps/hasura/migrations/masterbots/1718416395664_create_table_models_enum"

echo "Directory listing for migration:"
ls -la "$MIG_DIR"

echo -e "\n--- up.sql (first 200 lines) ---"
sed -n '1,200p' "$MIG_DIR/up.sql"

echo -e "\nChecking for down.sql:"
if [ -e "$MIG_DIR/down.sql" ]; then 
  echo "down.sql exists"
else 
  echo "down.sql missing"
fi

Length of output: 1882


🏁 Script executed:

#!/bin/bash
# Print down.sql to verify rollback steps
sed -n '1,200p' apps/hasura/migrations/masterbots/1718416395664_create_table_models_enum/down.sql

Length of output: 138


✅ Enums & rollback verified; application logic needs new model handlers

  • Generated schema (packages/mb-genql/generated/schema.ts) already includes the new entries:
    • GEMINI__FLASH__IMG
    • OPENAI__IMG
    • OPENAI__DALLE__2
    • OPENAI__DALLE__3
  • A down.sql is present and correctly drops the models_enum table as part of this initial‐creation migration.
  • In apps/masterbots.ai/app/actions/ai-main-call.ts, only the gemini-2.0-flash-exp value is explicitly handled. You’ll need to add cases (or fallback logic) for:
    gpt-image-1
    dall-e-2
    dall-e-3
🤖 Prompt for AI Agents
In
apps/hasura/migrations/masterbots/1718416395664_create_table_models_enum/up.sql
lines 20 to 23, the new image generation models are added to the enum, but the
application code in apps/masterbots.ai/app/actions/ai-main-call.ts only handles
the old model name 'gemini-2.0-flash-exp'. To fix this, update the
ai-main-call.ts file to add explicit handling cases or fallback logic for the
new model values 'gpt-image-1', 'dall-e-2', and 'dall-e-3' to ensure the
application correctly supports these new models.

'preference',
{
preferenceId: serial('preference_id').primaryKey().notNull(),
chatbotId: integer('chatbot_id').default(1),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reconsider hard-coded default value for chatbotId

The default value of 1 assumes a chatbot with ID 1 always exists. This could cause foreign key constraint violations.

Consider one of these alternatives:

-		chatbotId: integer('chatbot_id').default(1),
+		chatbotId: integer('chatbot_id'), // Make it required without default

Or make it nullable if preferences can exist without a chatbot:

-		chatbotId: integer('chatbot_id').default(1),
+		chatbotId: integer('chatbot_id'),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
chatbotId: integer('chatbot_id').default(1),
chatbotId: integer('chatbot_id'), // Make it required without default
🤖 Prompt for AI Agents
In packages/mb-drizzle/src/drizzle/schema.ts at line 136, the field chatbotId
has a hard-coded default value of 1, which assumes a chatbot with ID 1 always
exists and may cause foreign key constraint violations. To fix this, either
remove the default value and require explicit assignment, make the chatbotId
field nullable if preferences can exist without a chatbot, or implement a safer
defaulting mechanism that ensures the referenced chatbot exists before assigning
a default ID.

name: text().notNull(),
description: text(),
avatar: text(),
createdBy: text('created_by').notNull(),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add foreign key constraint for createdBy field

The createdBy field should reference the user table to maintain referential integrity. Currently, any arbitrary text can be inserted without validation.

Add a foreign key constraint in the table definition:

 		foreignKey({
+			columns: [table.createdBy],
+			foreignColumns: [user.userId],
+			name: 'chatbot_created_by_fkey',
+		}),
+		foreignKey({
 			columns: [table.defaultComplexity],

Note: You'll need to change the field type from text to uuid to match the user table's primary key:

-		createdBy: text('created_by').notNull(),
+		createdBy: uuid('created_by').notNull(),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
createdBy: text('created_by').notNull(),
// … in your columns definition
- createdBy: text('created_by').notNull(),
+ createdBy: uuid('created_by').notNull(),
// … later, in your table-level constraints
+ foreignKey({
+ columns: [table.createdBy],
+ foreignColumns: [user.userId],
+ name: 'chatbot_created_by_fkey',
+ }),
foreignKey({
columns: [table.defaultComplexity],
foreignColumns: [complexity.id],
name: 'chatbot_default_complexity_fkey',
}),
// …
🤖 Prompt for AI Agents
In packages/mb-drizzle/src/drizzle/schema.ts at line 45, the createdBy field is
defined as text without a foreign key constraint, allowing invalid data. Change
the type from text to uuid to match the user table's primary key, then add a
foreign key constraint referencing the user table's id column to enforce
referential integrity.

Comment on lines +336 to +378
export const socialFollowing = pgTable(
'social_following',
{
followerId: uuid('follower_id').notNull(),
followeeId: uuid('followee_id'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' })
.defaultNow()
.notNull(),
followeeIdChatbot: integer('followee_id_chatbot'),
},
(table) => [
index('idx_social_following_followee').using(
'btree',
table.followeeId.asc().nullsLast().op('uuid_ops'),
),
index('idx_social_following_follower').using(
'btree',
table.followerId.asc().nullsLast().op('uuid_ops'),
),
foreignKey({
columns: [table.followerId],
foreignColumns: [user.userId],
name: 'social_following_follower_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeId],
foreignColumns: [user.userId],
name: 'social_following_followee_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeIdChatbot],
foreignColumns: [chatbot.chatbotId],
name: 'social_following_followee_id_chatbot_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
check('social_following_check', sql`follower_id <> followee_id`),
],
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add primary key to prevent duplicate follow relationships

The social_following table lacks a primary key, which could allow duplicate follow relationships between the same users.

Add a composite primary key:

 		check('social_following_check', sql`follower_id <> followee_id`),
+		primaryKey({
+			columns: [table.followerId, table.followeeId, table.followeeIdChatbot],
+			name: 'social_following_pkey',
+		}),

Note: Adjust the primary key columns based on your business logic - you might only need followerId and one of the followee columns if they're mutually exclusive.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const socialFollowing = pgTable(
'social_following',
{
followerId: uuid('follower_id').notNull(),
followeeId: uuid('followee_id'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' })
.defaultNow()
.notNull(),
followeeIdChatbot: integer('followee_id_chatbot'),
},
(table) => [
index('idx_social_following_followee').using(
'btree',
table.followeeId.asc().nullsLast().op('uuid_ops'),
),
index('idx_social_following_follower').using(
'btree',
table.followerId.asc().nullsLast().op('uuid_ops'),
),
foreignKey({
columns: [table.followerId],
foreignColumns: [user.userId],
name: 'social_following_follower_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeId],
foreignColumns: [user.userId],
name: 'social_following_followee_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeIdChatbot],
foreignColumns: [chatbot.chatbotId],
name: 'social_following_followee_id_chatbot_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
check('social_following_check', sql`follower_id <> followee_id`),
],
)
export const socialFollowing = pgTable(
'social_following',
{
followerId: uuid('follower_id').notNull(),
followeeId: uuid('followee_id'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' })
.defaultNow()
.notNull(),
followeeIdChatbot: integer('followee_id_chatbot'),
},
(table) => [
index('idx_social_following_followee').using(
'btree',
table.followeeId.asc().nullsLast().op('uuid_ops'),
),
index('idx_social_following_follower').using(
'btree',
table.followerId.asc().nullsLast().op('uuid_ops'),
),
foreignKey({
columns: [table.followerId],
foreignColumns: [user.userId],
name: 'social_following_follower_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeId],
foreignColumns: [user.userId],
name: 'social_following_followee_id_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
foreignKey({
columns: [table.followeeIdChatbot],
foreignColumns: [chatbot.chatbotId],
name: 'social_following_followee_id_chatbot_fkey',
})
.onUpdate('restrict')
.onDelete('restrict'),
check('social_following_check', sql`follower_id <> followee_id`),
+ primaryKey({
+ columns: [table.followerId, table.followeeId, table.followeeIdChatbot],
+ name: 'social_following_pkey',
+ }),
],
)
🤖 Prompt for AI Agents
In packages/mb-drizzle/src/drizzle/schema.ts around lines 336 to 378, the
social_following table lacks a primary key, which can lead to duplicate follow
relationships. Add a composite primary key constraint including followerId and
the appropriate followee column(s) based on your business logic, such as
followerId and followeeId or followerId and followeeIdChatbot, to ensure
uniqueness and prevent duplicates.

threadId: uuid('thread_id').defaultRandom().notNull(),
userId: uuid('user_id'),
isPublic: boolean('is_public').default(true),
model: varchar({ length: 30 }).default('openAi').notNull(),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify default model value and reconsider composite primary key

  1. The default value 'openAi' must exist in the models_enum table
  2. The composite primary key on (threadId, slug) is redundant since threadId has a unique constraint

Consider simplifying the primary key:

-		primaryKey({ columns: [table.threadId, table.slug], name: 'thread_pkey' }),
+		// Remove composite PK since threadId is already unique
 		unique('thread_id_key').on(table.threadId),

Also applies to: 632-634


🏁 Script executed:

#!/bin/bash
# Verify if 'openAi' exists as a valid model name in any initialization scripts or migrations
fd -e sql -e ts | xargs rg -l "openAi|openai" | head -10

Length of output: 505


🏁 Script executed:

#!/bin/bash
echo "=== models_enum migration (create_table_models_enum) ==="
sed -n '1,200p' apps/hasura/migrations/masterbots/1718416395664_create_table_models_enum/up.sql

echo -e "\n=== alter_table_thread_create_column_model migration ==="
sed -n '1,200p' apps/hasura/migrations/masterbots/1718808699472_alter_table_thread_create_column_model/up.sql

echo -e "\n=== Thread table definition in schema.ts ==="
sed -n '580,650p' packages/mb-drizzle/src/drizzle/schema.ts

Length of output: 4258


Default model ‘openAi’ is valid; composite primary key is redundant

– Verified that ‘openAi’ is inserted in models_enum (see migration 1718416395664), so the default value is correct and foreign key will resolve.
– The composite primary key on (threadId, slug) is redundant because you already enforce uniqueness on both threadId and slug individually.

Please simplify the table definition accordingly, for example:

-    primaryKey({ columns: [table.threadId, table.slug], name: 'thread_pkey' }),
-    unique('thread_id_key').on(table.threadId),
+    // threadId alone is sufficient as primary key
+    primaryKey({ columns: [table.threadId], name: 'thread_pkey' }),
     unique('thread_slug_unique').on(table.slug),
     unique('thread_short_link_key').on(table.shortLink),

This will remove unnecessary redundancy without affecting data integrity.

🤖 Prompt for AI Agents
In packages/mb-drizzle/src/drizzle/schema.ts at line 600 and also lines 632-634,
the default value 'openAi' for the model column is valid as it exists in the
models_enum table, so no change needed there. However, the composite primary key
on (threadId, slug) is redundant because both threadId and slug have unique
constraints individually. To fix this, remove the composite primary key
definition and rely on the existing unique constraints on threadId and slug to
maintain data integrity, simplifying the table schema.

'prompt_chatbot',
{
promptId: integer('prompt_id').notNull(),
chabotId: integer('chabot_id').notNull(),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in column name

The column name chabotId should be chatbotId to maintain naming consistency.

-		chabotId: integer('chabot_id').notNull(),
+		chatbotId: integer('chatbot_id').notNull(),

Also update the foreign key reference:

-			columns: [table.chabotId],
+			columns: [table.chatbotId],

And the primary key:

-			columns: [table.promptId, table.chabotId],
+			columns: [table.promptId, table.chatbotId],
🤖 Prompt for AI Agents
In packages/mb-drizzle/src/drizzle/schema.ts at line 430, correct the typo in
the column name from 'chabotId' to 'chatbotId' to maintain naming consistency.
Additionally, update any foreign key references and the primary key definition
that use this column name to reflect the corrected 'chatbotId'.

@AndlerRL AndlerRL merged commit efddd85 into main May 24, 2025
2 checks passed
@AndlerRL
Copy link
Member Author

@AndlerRL
Copy link
Member Author

sheriffjimoh added a commit that referenced this pull request Sep 9, 2025
… schema, and improve ui components (#495)

* 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)

* refactor: use chat and continue thread + continue conversation fallback (#432)

* refactor: use chat and continue generation

* fix: uniq slug and id gen (#433)

* fix: uniq thread + msg slug gen

* style: formatting

* fix: thread user attachments state upt

* perf: impr thread component at all pages + mobile tweaks

* refactor: thread-component card

* chore: restore continue generation v1

* feat(impr): thread component card

* fix: admin panel n actions

* fix: fetch getThreads

* chore: continue conversation v1.2

* chore: continue and update thread content

* chore: add ui control continue generation state

* chore: fix infinity loop

* chore(impr): enable upt msg table permission

* fix: seo thread fetch

* chore: style formating

* fix(impr): continued thread title + thread component reusability

* chore: refactor loadings + extending sonners

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>

* feat: add gemini provider (#437)

* feat: add gemini provider

* chore: update icons

* feat: impr continuing thread tags + accordion first msg toggle (#435)

* feat(wip): impr continuing thread tags + accordion first msg toggle

* feat(impr): continuing thread tags + accordion at first message + header mobile tweak

* style(impr): mobile thread-component x-axis space

* perf(style): coderabbitai feedbacks

* fix: css typo

* perf: sendMessageFromResponse clicked guard + continued thread tags label tweak

* chore: user thread panel clean up

* fix: user-thread-panel infinite loader

* perf: impr shared accordion animation and ux

* style: defaultAccordionState comments loc

* fix: record type warning, hasura updateMessage

* fix: getThread user data, shared-accordion

* fix: coderabbitai observations

* fix: impr file management per llm, multimodel feat flag, chat tool labels, parent thread guard

* fix: tunningUserContent parentThread condition

* fix: feature flag typo

* feat: profile page thread popup feature flag and tweaks  (#434)

* update

* fix: update

* update

* update

* update

* update

* refactor: profile page threads pop up

* fix: update config

* fix: update

* fix: update

* fix: make profile page scroll on hero

* fix: bot make popup and scroll

* fix: make profile page sidebar scroll independently

* fix: make profile page sidebar scroll independently

* fix: check the category along the chatbot when it's not checked

* fix: check the category along the chatbot when it's not checked

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
Co-authored-by: Roberto Lucas <andler@bitcash.org>

* feat: add new llm models (#444)

* feat-add-models

* feat-add-models

* feat-add-models

* chore: add model

* fix: typo

* chore: add toggler color

* perf(impr): thread llm context, last question & response + new models seeds (#447)

* feat(wip): thread llm context, prev questions

* fix: previousQuestionsString slice

* fix: clickedContentId in followingQuestionsPrompt

* feat: isContinued + model type in message table

* fix: ts typo + sendMessageFromResponse callback call

* fix: ts typo

* fix: bot profile page view (#449)

* fix(wip): bot profile thread list

* style: formatting

* fix: new chats and share + og img (#451)

* fix: new chat state reset

* fix: genql gen + share link check

* fix: og img

* fix: duplicate role permission in msg table

* feat: initial continuation logic flow (#450)

* chore: restore base version

* chore: add new logic and hooks

* chore: fix providers file

* chore: improve continuation prompt

* chore: add exlucision flag

* chore: add better handler

* chore: updated flow + experimental delay

* chore: extended time

* chore(impr): streamDelayMs experimental feat flag

* style: formatting

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* fix: profile sidebar cat opt render (#453)

* fix: profile sidebar cat opt render

* chore: clean-up

* [masterbots.ai] refactor: slug generation logic with improved uniqueness and type support (#456)

* fix: slugify fn

* chore: devMode logs

* fix: uniq slug gen fn nanoid flag typo

* feat: sentry logs in webapp (#457)

* fix(impr): llm enum data, thread creation, ts, and log behavior (#458)

* fix: slugify first request delay incr + genql ts, seeds & model migration upt

* fix: create thread & msg ts

* fix(impr): profile page bugs & tweaks v1 4/15/25 (#455)

* update

* fix: update

* update

* update

* update

* update

* fix: use the user avatar or robohash

* fix: added avater to user menu

* fix: user avatar

* fix: reset search input when filter by category or chatbot

* fix: personal chat browse provider + username chk in sign up

* chore: clean duplicated if condition signup

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* refactor: continuation flow (#460)

* impr: continuation logic flow

* impr: continuation logic flow

* chore: update createImprovementPrompt

* chore: upt logs

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* feat: models table, enum type, and refactor chat msg deduplication logic (#462)

* feat: models table

* style: formatting

* fix: continuation accordion content

* fix: sql + metadata typo

* fix: db migrations and messages uniqby condition (#463)

* fix: db migrations + messages uniqby condition

* fix: typo

* perf(impr): verify duplicate message return condition

* chore: upt default available models

* perf(impr): reassign continued prompt

* chore: incr fn stream max duration

* fix: mob prof sidebar + sign-up pw verif + username chk (#464)

* fix: mob prof sidebar + sign-up pw verif + username chk

* chore: upt genql gen

* perf(impr): profile navigation

* feat: model selector (#466)

* wip: model selector query

* wip: model selector query

* chore: improve funtions

* chore: add coderabbit suggestion

* chore: add hasura permissions, models table

* style: formatting

* chore: fix get model client type

* chore: add model

---------

Co-authored-by: Roberto Romero Lucas <contact@andler.dev>

* chore: impr models (#472)

* chore: fix model name and condition (#473)

* refactor: user fetching code (#471)

* refactor: profile sidebar ui, upt styling, and disable prefetch (#470)

* chore: remove prefetch on sidebar & profile navigation

* perf: impr profile sidebar

* fix: infinite scroll load more fetch

* perf(impr): google sign-in

* perf(impr): session loaders tweak

* perf: impr categoriesId obtention

* fix: tailwind typo

* chore(impr): pro user guard in model selector

* chore: category label upt to topic

* chore: rm dev mode guard (#476)

* feat: add reasoning compatibility (#480)

* feat: add resoning stable

* chore: add reasoning stable v

* chore: activate reasoning

* chore: activate reasoning

* feat: pro users whitelist (#481)

* feat(wip): whitelist pro users

* chore: add whitelist pro users + page size fetch

* perf(impr): following question impr prompt

* fix: pro whitelist users clean up

* feat: user account setting  (#468)

* update

* fix: update

* update

* update

* update

* update

* feat: imple account setting

* feat: added dialog to delete button

* feat: update user deletion func

* fix: move back exmaples files

* fix: update

* fix: user account scheduling api

* fix: user account deletion request function

* refactor: account deletion request api

* fix: user account request and thread deletion

* fix: added permission and account deletion page

* fix: update on permission

* fix: enable new col permission

* fix: profile side bar

* fix: update

* fix: function rerendering

* fix: update route

* chore(impr): preferences actions and ui tweaks

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* chore: enable twitter pixel track (#479)

* chore: enable twitter pixel track

* perf(impr): twitter ads availability + dynamic config

* feat: impr profile navigation page (#478)

* fix(wip): subscriptions page render

* feat(impr): profile navigation + page ui tweaks

* style: lintin + formatting

* style(css): nav links px on mob

* fix: goToProfile in mob prof sidebar

* fix: build

* fix: thread popup opening at nav

* chore: enable preferences nav on prod

* feat: image generation  (#486)

* feat: add image generation support - gemini provider

* chore: add mineType

* chore: add conditional checks

* chore: upt model enums & list

* chore: hasura, set icl seeds chunks (#484)

* chore: hasura, set icl seeds chunks

* chore: track backup icl seed loc to lfs

* chore(seeds): uncomment phase 3 topics & add new chatbots + icl metadata rel

* chore: upt phase 3 init config seeds, adding rel

* fix: example seeds integrity

* test: incr hasura max req body

* revert: cloudbuild og config

* chore: restore skipped seed lines

* fix: thread rendering (#487)

* fix: thread list render states

* chore: linting & format

* fix: thread pop-up on refresh

* fix: user table selection

* fix(impr): type safety for image data and refactor model enums in chat (#489)

* fix: image generation flow

* chore: impr gemini generation logic

* fix: build issue

* chore: change subscription page

* chore: change subscription page + lint

* chore: user pref disable options

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>

* fix: add hotfix image generation

* chore: add more image models

* fix: models_enum values + genql upt

* feat: improved subscription section (#491)

* feat: add improved subscription section

* feat: add type

* chore: add conditional dislay

* feat: add username tags

* chore: add new order and benefits

* fix: thread empty state on user profile (#490)

* update

* fix: update

* update

* update

* update

* update

* feat: added empty state to user profile page

* feat: added empty state to user profile page

* fix: update

* fix: update

* fix: account creation slug issue

* chore: restore public models table select permissions + clean up

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>
Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* feat(wip): web search v2 (#494)

* feat(wip): web search

* feat(wip): thread config actions

* feat(wip): share cta impr

* chore: upt domain slugs list

* chore: comment legacy getWebSearchTool

* fix: preference insert

* wip: user preferences set

* fix: typo

* fix: updateUser data upt

---------

Co-authored-by: Brandon Fernández <31634868+Bran18@users.noreply.github.com>
Co-authored-by: Jimoh sherifdeen <63134009+sheriffjimoh@users.noreply.github.com>
Co-authored-by: bran18 <andreyfdez18@gmail.com>
Co-authored-by: Brandon fernandez <brandonfernandez@Brandons-Mac-mini.local>
sheriffjimoh added a commit that referenced this pull request Sep 10, 2025
… schema, and improve ui components (#495)

* 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)

* refactor: use chat and continue thread + continue conversation fallback (#432)

* refactor: use chat and continue generation

* fix: uniq slug and id gen (#433)

* fix: uniq thread + msg slug gen

* style: formatting

* fix: thread user attachments state upt

* perf: impr thread component at all pages + mobile tweaks

* refactor: thread-component card

* chore: restore continue generation v1

* feat(impr): thread component card

* fix: admin panel n actions

* fix: fetch getThreads

* chore: continue conversation v1.2

* chore: continue and update thread content

* chore: add ui control continue generation state

* chore: fix infinity loop

* chore(impr): enable upt msg table permission

* fix: seo thread fetch

* chore: style formating

* fix(impr): continued thread title + thread component reusability

* chore: refactor loadings + extending sonners

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>

* feat: add gemini provider (#437)

* feat: add gemini provider

* chore: update icons

* feat: impr continuing thread tags + accordion first msg toggle (#435)

* feat(wip): impr continuing thread tags + accordion first msg toggle

* feat(impr): continuing thread tags + accordion at first message + header mobile tweak

* style(impr): mobile thread-component x-axis space

* perf(style): coderabbitai feedbacks

* fix: css typo

* perf: sendMessageFromResponse clicked guard + continued thread tags label tweak

* chore: user thread panel clean up

* fix: user-thread-panel infinite loader

* perf: impr shared accordion animation and ux

* style: defaultAccordionState comments loc

* fix: record type warning, hasura updateMessage

* fix: getThread user data, shared-accordion

* fix: coderabbitai observations

* fix: impr file management per llm, multimodel feat flag, chat tool labels, parent thread guard

* fix: tunningUserContent parentThread condition

* fix: feature flag typo

* feat: profile page thread popup feature flag and tweaks  (#434)

* update

* fix: update

* update

* update

* update

* update

* refactor: profile page threads pop up

* fix: update config

* fix: update

* fix: update

* fix: make profile page scroll on hero

* fix: bot make popup and scroll

* fix: make profile page sidebar scroll independently

* fix: make profile page sidebar scroll independently

* fix: check the category along the chatbot when it's not checked

* fix: check the category along the chatbot when it's not checked

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>
Co-authored-by: Roberto Lucas <andler@bitcash.org>

* feat: add new llm models (#444)

* feat-add-models

* feat-add-models

* feat-add-models

* chore: add model

* fix: typo

* chore: add toggler color

* perf(impr): thread llm context, last question & response + new models seeds (#447)

* feat(wip): thread llm context, prev questions

* fix: previousQuestionsString slice

* fix: clickedContentId in followingQuestionsPrompt

* feat: isContinued + model type in message table

* fix: ts typo + sendMessageFromResponse callback call

* fix: ts typo

* fix: bot profile page view (#449)

* fix(wip): bot profile thread list

* style: formatting

* fix: new chats and share + og img (#451)

* fix: new chat state reset

* fix: genql gen + share link check

* fix: og img

* fix: duplicate role permission in msg table

* feat: initial continuation logic flow (#450)

* chore: restore base version

* chore: add new logic and hooks

* chore: fix providers file

* chore: improve continuation prompt

* chore: add exlucision flag

* chore: add better handler

* chore: updated flow + experimental delay

* chore: extended time

* chore(impr): streamDelayMs experimental feat flag

* style: formatting

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* fix: profile sidebar cat opt render (#453)

* fix: profile sidebar cat opt render

* chore: clean-up

* [masterbots.ai] refactor: slug generation logic with improved uniqueness and type support (#456)

* fix: slugify fn

* chore: devMode logs

* fix: uniq slug gen fn nanoid flag typo

* feat: sentry logs in webapp (#457)

* fix(impr): llm enum data, thread creation, ts, and log behavior (#458)

* fix: slugify first request delay incr + genql ts, seeds & model migration upt

* fix: create thread & msg ts

* fix(impr): profile page bugs & tweaks v1 4/15/25 (#455)

* update

* fix: update

* update

* update

* update

* update

* fix: use the user avatar or robohash

* fix: added avater to user menu

* fix: user avatar

* fix: reset search input when filter by category or chatbot

* fix: personal chat browse provider + username chk in sign up

* chore: clean duplicated if condition signup

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* refactor: continuation flow (#460)

* impr: continuation logic flow

* impr: continuation logic flow

* chore: update createImprovementPrompt

* chore: upt logs

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* feat: models table, enum type, and refactor chat msg deduplication logic (#462)

* feat: models table

* style: formatting

* fix: continuation accordion content

* fix: sql + metadata typo

* fix: db migrations and messages uniqby condition (#463)

* fix: db migrations + messages uniqby condition

* fix: typo

* perf(impr): verify duplicate message return condition

* chore: upt default available models

* perf(impr): reassign continued prompt

* chore: incr fn stream max duration

* fix: mob prof sidebar + sign-up pw verif + username chk (#464)

* fix: mob prof sidebar + sign-up pw verif + username chk

* chore: upt genql gen

* perf(impr): profile navigation

* feat: model selector (#466)

* wip: model selector query

* wip: model selector query

* chore: improve funtions

* chore: add coderabbit suggestion

* chore: add hasura permissions, models table

* style: formatting

* chore: fix get model client type

* chore: add model

---------

Co-authored-by: Roberto Romero Lucas <contact@andler.dev>

* chore: impr models (#472)

* chore: fix model name and condition (#473)

* refactor: user fetching code (#471)

* refactor: profile sidebar ui, upt styling, and disable prefetch (#470)

* chore: remove prefetch on sidebar & profile navigation

* perf: impr profile sidebar

* fix: infinite scroll load more fetch

* perf(impr): google sign-in

* perf(impr): session loaders tweak

* perf: impr categoriesId obtention

* fix: tailwind typo

* chore(impr): pro user guard in model selector

* chore: category label upt to topic

* chore: rm dev mode guard (#476)

* feat: add reasoning compatibility (#480)

* feat: add resoning stable

* chore: add reasoning stable v

* chore: activate reasoning

* chore: activate reasoning

* feat: pro users whitelist (#481)

* feat(wip): whitelist pro users

* chore: add whitelist pro users + page size fetch

* perf(impr): following question impr prompt

* fix: pro whitelist users clean up

* feat: user account setting  (#468)

* update

* fix: update

* update

* update

* update

* update

* feat: imple account setting

* feat: added dialog to delete button

* feat: update user deletion func

* fix: move back exmaples files

* fix: update

* fix: user account scheduling api

* fix: user account deletion request function

* refactor: account deletion request api

* fix: user account request and thread deletion

* fix: added permission and account deletion page

* fix: update on permission

* fix: enable new col permission

* fix: profile side bar

* fix: update

* fix: function rerendering

* fix: update route

* chore(impr): preferences actions and ui tweaks

---------

Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* chore: enable twitter pixel track (#479)

* chore: enable twitter pixel track

* perf(impr): twitter ads availability + dynamic config

* feat: impr profile navigation page (#478)

* fix(wip): subscriptions page render

* feat(impr): profile navigation + page ui tweaks

* style: lintin + formatting

* style(css): nav links px on mob

* fix: goToProfile in mob prof sidebar

* fix: build

* fix: thread popup opening at nav

* chore: enable preferences nav on prod

* feat: image generation  (#486)

* feat: add image generation support - gemini provider

* chore: add mineType

* chore: add conditional checks

* chore: upt model enums & list

* chore: hasura, set icl seeds chunks (#484)

* chore: hasura, set icl seeds chunks

* chore: track backup icl seed loc to lfs

* chore(seeds): uncomment phase 3 topics & add new chatbots + icl metadata rel

* chore: upt phase 3 init config seeds, adding rel

* fix: example seeds integrity

* test: incr hasura max req body

* revert: cloudbuild og config

* chore: restore skipped seed lines

* fix: thread rendering (#487)

* fix: thread list render states

* chore: linting & format

* fix: thread pop-up on refresh

* fix: user table selection

* fix(impr): type safety for image data and refactor model enums in chat (#489)

* fix: image generation flow

* chore: impr gemini generation logic

* fix: build issue

* chore: change subscription page

* chore: change subscription page + lint

* chore: user pref disable options

---------

Co-authored-by: bran18 <andreyfdez18@gmail.com>

* fix: add hotfix image generation

* chore: add more image models

* fix: models_enum values + genql upt

* feat: improved subscription section (#491)

* feat: add improved subscription section

* feat: add type

* chore: add conditional dislay

* feat: add username tags

* chore: add new order and benefits

* fix: thread empty state on user profile (#490)

* update

* fix: update

* update

* update

* update

* update

* feat: added empty state to user profile page

* feat: added empty state to user profile page

* fix: update

* fix: update

* fix: account creation slug issue

* chore: restore public models table select permissions + clean up

---------

Co-authored-by: Roberto Lucas <andler@bitcash.org>
Co-authored-by: Roberto Lucas <andler.dev@gmail.com>

* feat(wip): web search v2 (#494)

* feat(wip): web search

* feat(wip): thread config actions

* feat(wip): share cta impr

* chore: upt domain slugs list

* chore: comment legacy getWebSearchTool

* fix: preference insert

* wip: user preferences set

* fix: typo

* fix: updateUser data upt

---------

Co-authored-by: Brandon Fernández <31634868+Bran18@users.noreply.github.com>
Co-authored-by: Jimoh sherifdeen <63134009+sheriffjimoh@users.noreply.github.com>
Co-authored-by: bran18 <andreyfdez18@gmail.com>
Co-authored-by: Brandon fernandez <brandonfernandez@Brandons-Mac-mini.local>
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