Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(backend): refactor chat service to support creating chats with i… #169

Merged
merged 1 commit into from
Mar 7, 2025

Conversation

Sma1lboy
Copy link
Collaborator

@Sma1lboy Sma1lboy commented Mar 7, 2025

…nitial messages

Summary by CodeRabbit

  • New Features

    • Initiate chat sessions with an integrated opening message for a smoother conversation start.
    • Project chats now automatically feature an introductory message derived from project descriptions.
  • Improvements

    • Optimized chat history management for more consistent message handling.
    • Enhanced message details now include timestamps and status indicators for better context.

Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

This pull request modifies several components of the chat functionality. In the chat module, the Message entity is removed from TypeORM configuration. In the chat service, method signatures have been updated (with explicit return types removed) and a new method createChatWithMessage has been introduced to create a chat along with an initial message. Additionally, the Message model has been decoupled from TypeORM with added GraphQL fields, and the project service now invokes the new chat creation method while noting a pending improvement on chat copying during project forking.

Changes

File(s) Change Summary
backend/src/chat/chat.module.ts Removed the Message entity from TypeOrmModule.forFeature imports; the module now only imports Chat and User, with no changes to providers or exports.
backend/src/chat/chat.service.ts Updated method signatures by removing explicit return types, removed logging in getChatDetails, adjusted clearChatHistory and saveMessage, and added a new createChatWithMessage method to create chats with an initial message.
backend/src/chat/message.model.ts Removed TypeORM decorators from the Message class, decoupling it from the database; added new GraphQL-exposed fields (createdAt, updatedAt, isActive, isDeleted) while retaining existing fields.
backend/src/project/project.service.ts Replaced createChat with createChatWithMessage to include an initial message (using input.description) during project chat creation; added a FIXME comment regarding correct chat copying during project forking.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant CS as ChatService
    participant U as User Repository
    participant DB as Database

    C->>CS: createChatWithMessage(userId, { title, message })
    CS->>U: Retrieve user by userId
    U-->>CS: Return user data (or error)
    alt User exists
      CS->>DB: Save new chat with title
      DB-->>CS: Return chat with ID
      CS->>DB: Save initial message (using chat ID & message)
      DB-->>CS: Return updated chat
      CS-->>C: Return chat with new message
    else User not found
      CS-->>C: Return error
    end
Loading

Possibly related PRs

  • feat: adding chat isolation #84: Modifications in the ChatService, particularly the addition of the createChatWithMessage method, align closely with the changes in this pull request.

Suggested reviewers

  • ZHallen122

Poem

I'm a rabbit with a hop so light,
Tweaking chat code by day and night,
Removed the old, embraced the new,
With messages now in vibrant view.
Bounding through code with a cheerful leap,
Celebrating changes, awake or asleep!
🐇✨

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.

backend/src/chat/chat.module.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/chat/message.model.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/chat/chat.service.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 1 others
✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
backend/src/project/project.service.ts (1)

554-554: Resolve the FIXME by implementing proper chat copying logic.

You have a FIXME indicating the need to copy the original chat. I can help propose a solution to clone or replicate the messages from the source chat if desired. Let me know if you'd like me to open a new issue or provide a snippet.

backend/src/chat/message.model.ts (1)

32-52: Manually handle lifecycle fields after removing TypeORM decorators.

With TypeORM removed, createdAt, updatedAt, isActive, and isDeleted will no longer be auto-managed. Ensure you have the necessary logic in your codebase to correctly initialize and update these fields (e.g., setting updatedAt on edits) so data integrity remains intact.

backend/src/chat/chat.service.ts (4)

49-49: Consider adding explicit return type for better code documentation

The return type annotation has been removed from this method. While TypeScript can infer the return type, explicit return types improve code readability and serve as documentation.

- async getChatHistory(chatId: string) {
+ async getChatHistory(chatId: string): Promise<any[]> {

111-146: Great implementation of the new createChatWithMessage method

This new method successfully implements the core feature of this PR: creating a chat with an initial message in one operation. The code properly handles:

  1. User verification
  2. Chat creation
  3. Message generation with appropriate ID format
  4. Linking the message to the chat

One suggestion to consider: add error handling for the chat save operation.

  // Save the chat first to get an ID
- const savedChat = await this.chatRepository.save(newChat);
+ let savedChat;
+ try {
+   savedChat = await this.chatRepository.save(newChat);
+ } catch (error) {
+   throw new Error(`Failed to create chat: ${error.message}`);
+ }

190-194: Enhanced error handling in saveMessage

Good addition of a null check for chat existence. Consider adding explicit return type for better code documentation.

- async saveMessage(chatId: string, messageContent: string, role: MessageRole) {
+ async saveMessage(chatId: string, messageContent: string, role: MessageRole): Promise<any> {

111-146: Consider adding transaction support for chat and message creation

The current implementation creates a chat and then adds a message in two separate database operations. Consider using TypeORM transactions to ensure atomicity.

async createChatWithMessage(
  userId: string,
  newChatInput: { title: string; message: string },
): Promise<Chat> {
  const user = await this.userRepository.findOne({ where: { id: userId } });
  if (!user) {
    throw new Error('User not found');
  }

+ // Use a transaction to ensure atomicity
+ return await this.chatRepository.manager.transaction(async transactionalEntityManager => {
    // Create a new chat with the initial message
    const newChat = this.chatRepository.create({
      title: newChatInput.title,
      messages: [],
      createdAt: new Date(),
      updatedAt: new Date(),
      user: user,
    });

    // Save the chat first to get an ID
-   const savedChat = await this.chatRepository.save(newChat);
+   const savedChat = await transactionalEntityManager.save(newChat);

    // Create the message with the chat's ID as a prefix
    const message = {
      id: `${savedChat.id}/0`,
      content: newChatInput.message,
      role: MessageRole.User,
      createdAt: new Date(),
      updatedAt: new Date(),
      isActive: true,
      isDeleted: false,
    };

    // Update the chat with the message
    savedChat.messages = [message];
-   return await this.chatRepository.save(savedChat);
+   return await transactionalEntityManager.save(savedChat);
+ });
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f89451 and 0c20cdb.

📒 Files selected for processing (4)
  • backend/src/chat/chat.module.ts (1 hunks)
  • backend/src/chat/chat.service.ts (6 hunks)
  • backend/src/chat/message.model.ts (1 hunks)
  • backend/src/project/project.service.ts (2 hunks)
🔇 Additional comments (8)
backend/src/chat/chat.module.ts (1)

14-14: Ensure all references to the removed Message entity are fully updated.

Removing Message from forFeature indicates a shift away from TypeORM for messages. Please verify that no legacy references to TypeORM-based Message remain in your codebase, as they could lead to runtime errors.

backend/src/project/project.service.ts (1)

193-195: Validate and sanitize the input.description prior to creating the initial chat message.

By passing input.description to createChatWithMessage, you risk potential XSS or injection if the input is not sanitized. Please verify user input integrity and confirm that empty or undefined values are handled gracefully.

backend/src/chat/chat.service.ts (6)

3-3: Nice addition of the MessageRole import

This import helps maintain type safety when working with message roles in the chat service.


105-105: Minor code cleanup

This is a small syntax improvement, using the shorthand object property notation.


167-167: Improved clarity in clearChatHistory

This change makes it more explicit that the messages array is being reset, which improves code readability.


196-198: Defensive programming to prevent null reference errors

This is a good practice - checking if the messages array exists before attempting to use it prevents potential runtime errors.


200-201: Clear message ID generation pattern

The comment clarifies how message IDs are constructed, which is helpful for maintenance.


219-219: Updated relations to include user

This ensures the user data is eagerly loaded when fetching a chat, which aligns with the new functionality.

@Sma1lboy Sma1lboy merged commit 6bfe5ac into main Mar 7, 2025
3 of 4 checks passed
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.

2 participants