Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix/isValidMessage #5579

Closed

Conversation

code-october
Copy link
Contributor

@code-october code-october commented Oct 3, 2024

💻 变更类型 | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

🔀 变更说明 | Description of Change

  • 增加错误响应的判断(检测是否为包含 error 字段的 json)
  • 总结历史的请求也判断消息是否异常

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Introduced message validation to ensure only valid messages are processed for summarization.
    • Enhanced session management with improved uniqueness of session and message identifiers.
  • Bug Fixes

    • Updated logic to prevent invalid messages from affecting session memory.
  • Chores

    • Refined migration logic for older sessions to ensure consistent configurations and default values.

Copy link

vercel bot commented Oct 3, 2024

@code-october is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes in this pull request primarily enhance the message handling and session management functionality within the app/store/chat.ts file. A new function, isValidMessage, is introduced to validate messages based on specific criteria. This function is integrated into the summarizeSession method to ensure only valid messages are processed. Additionally, the migration logic for session data is refined to improve the uniqueness of identifiers and to maintain consistency in session configurations.

Changes

File Change Summary
app/store/chat.ts - Added isValidMessage function to validate messages.
- Updated summarizeSession to use isValidMessage for message validation.
- Refined migration logic for session IDs using nanoid().
- Set default values for compressModel and compressProviderName in session configuration.
test/isValidMessage.test.ts - Added tests for the isValidMessage function covering various message scenarios.

Possibly related PRs

Suggested reviewers

  • Dogtiti
  • lloydzhou

Poem

🐇 In the chat where messages flow,
A new check to help us know,
If a message's fit to share,
Validity handled with care.
With unique IDs, our sessions gleam,
In the world of chat, we dream! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dd793e0 and fe9c31c.

📒 Files selected for processing (1)
  • test/isValidMessage.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/isValidMessage.test.ts

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai 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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cea5b91 and a039690.

📒 Files selected for processing (1)
  • app/store/chat.ts (2 hunks)

Comment on lines 697 to 707
if (message.startsWith("```") && message.endsWith("```")) {
const jsonString = message.slice(3, -3).trim();
try {
const jsonObject = JSON.parse(jsonString);
if (jsonObject.error) {
return false;
}
} catch (e) {
console.log("Invalid JSON format.");
}
}
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

Ensure message is a string before invoking string methods

In the isValidMessage function, string methods startsWith and endsWith are called on message without verifying that message is indeed a string. If message is not a string, this can lead to runtime errors.

To prevent potential errors, check if message is a string before invoking string methods.

Apply this diff to add a type check:

+              if (typeof message !== "string") {
+                return false;
+              }
               if (message.startsWith("```") && message.endsWith("```")) {
                 const jsonString = message.slice(3, -3).trim();
                 try {
                   const jsonObject = JSON.parse(jsonString);
                   if (jsonObject.error) {
                     return false;
                   }
                 } catch (e) {
                   console.log("Invalid JSON format.");
+                  return false;
                 }
               }
-              return typeof message === "string" && !message.startsWith("```json");
+              return !message.startsWith("```json");

Comment on lines 698 to 704
const jsonString = message.slice(3, -3).trim();
try {
const jsonObject = JSON.parse(jsonString);
if (jsonObject.error) {
return false;
}
} catch (e) {
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

Simplify JSON extraction and improve accuracy

The current implementation checks for messages enclosed in triple backticks and attempts to parse the content as JSON. However, it might be more precise to specifically check for messages starting with ```json to accurately identify JSON-formatted messages.

Consider adjusting the function to enhance accuracy:

-              if (message.startsWith("```") && message.endsWith("```")) {
-                const jsonString = message.slice(3, -3).trim();
+              if (typeof message === "string" && message.startsWith("```json") && message.endsWith("```")) {
+                const jsonString = message.slice(7, -3).trim();
                 try {
                   const jsonObject = JSON.parse(jsonString);
                   if (jsonObject.error) {
                     return false;
                   }
                 } catch (e) {
                   console.log("Invalid JSON format.");
                   return false;
                 }
               }
-              return typeof message === "string" && !message.startsWith("```json");
+              return true;

This refactor:

  • Ensures the message is a string before processing.
  • Checks specifically for JSON code blocks starting with ```json.
  • Slices the content correctly to extract the JSON string.
  • Returns false immediately if JSON parsing fails.
  • Returns true at the end, assuming all invalid conditions have been checked.

Comment on lines 705 to 706
console.log("Invalid JSON format.");
}
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

Return false when JSON parsing fails

In the catch block of isValidMessage, when JSON parsing fails, the function logs "Invalid JSON format." but does not return false. This means that messages with invalid JSON will not be correctly marked as invalid.

Consider returning false when JSON parsing fails to ensure invalid messages are properly handled.

Apply this diff to return false when JSON parsing fails:

                 } catch (e) {
                   console.log("Invalid JSON format.");
+                  return false;
                 }
📝 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
console.log("Invalid JSON format.");
}
console.log("Invalid JSON format.");
return false;
}

@@ -681,6 +681,7 @@ export const useChatStore = createPersistStore(
},
onFinish(message) {
console.log("[Memory] ", message);
if (!isValidMessage(message)) return;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Potential unvalidated message processing detected in app/store/chat.ts at line 696.

Please ensure that isValidMessage is invoked consistently wherever messages are processed to maintain validation integrity.

🔗 Analysis chain

Verify that message validation is consistently applied

In the onFinish callback, the check if (!isValidMessage(message)) return; ensures that invalid messages are not processed. To maintain consistency and robustness, ensure that all instances where messages are processed include validation using isValidMessage.

Run the following script to check for other message handling without validation:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find instances where messages are handled without validation.
# Expected: All message processing should involve validation via isValidMessage.

rg --type ts --no-heading --line-number --color never 'function\s+\w+\(.*message.*\)' app/store/ | while read -r line; do
  file=$(echo "$line" | cut -d: -f1)
  lineno=$(echo "$line" | cut -d: -f2)
  function_def=$(echo "$line" | cut -d: -f3-)
  function_body=$(awk "NR>$lineno && NR<($lineno+20)" "$file")
  if ! echo "$function_body" | grep -q "isValidMessage"; then
    echo "Potential unvalidated message in $file:$lineno - $function_def"
  fi
done

Length of output: 2295

Copy link
Contributor

github-actions bot commented Oct 3, 2024

Your build has completed!

Preview deployment

@Dogtiti
Copy link
Member

Dogtiti commented Oct 8, 2024

下个版本会加上jest,到时可以更新主分支加一点测试用例方便review ~

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


Jest will be added to the next version. At that time, the main branch can be updated and some test cases can be added to facilitate review ~

@Dogtiti
Copy link
Member

Dogtiti commented Oct 11, 2024

可以更新一下代码,目前主分支已经加上了jest,可以补充一些测试用例~

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


You can update the code. Currently, jest has been added to the main branch. You can add some test cases~

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: 1

🧹 Outside diff range and nitpick comments (1)
app/store/chat.ts (1)

704-714: Ensure consistent language in code comments

The comments within the isValidMessage function are in Chinese. For consistency across the codebase, consider translating the comments to English.

Apply this diff to update the comments:

        try {
-          // 返回 json 格式消息,含 error.message 字段,判定为错误回复,否则为正常回复
+          // If the JSON object contains error.message, it's an error response; otherwise, it's a normal response
          const jsonObject = JSON.parse(jsonString);
          if (jsonObject?.error?.message) {
            return false;
          }
          return true;
        } catch (e) {
          console.log("Invalid JSON format.");
-          // 非 json 格式,大概率是正常回复
+          // Non-JSON format, most likely a normal response
          return true;
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a039690 and 4bb52b2.

📒 Files selected for processing (1)
  • app/store/chat.ts (2 hunks)
🧰 Additional context used

@code-october
Copy link
Contributor Author

测试用例暂时还不太清楚怎么添加,目前就是想覆盖这类错误提示,消息类型是不带json语言注释的代码块,其中包含error.message 字段:

image

image

image

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


It’s not yet clear how to add test cases. Currently, I just want to cover this type of error prompt. The message type is a code block without json language annotation, which contains the error.message field:

image

image

image

@Dogtiti
Copy link
Member

Dogtiti commented Oct 12, 2024

可以将你这个函数导出
然后在test文件夹下参考有一个测试示例
目的是看你这里的修改能覆盖哪些情况

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


You can export your function
Then refer to a test example in the test folder

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: 1

🧹 Outside diff range and nitpick comments (1)
app/store/chat.ts (1)

726-726: Approve message validation in summarizeSession

The addition of the isValidMessage check in the summarizeSession function is a good improvement. It ensures that only valid messages are processed during summarization, which can prevent potential errors or unexpected behavior.

Consider adding some error logging when an invalid message is encountered:

- if (!isValidMessage(message)) return;
+ if (!isValidMessage(message)) {
+   console.warn("Invalid message encountered during summarization:", message);
+   return;
+ }

This will help with debugging and monitoring the quality of messages being processed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4bb52b2 and 7d7ca64.

📒 Files selected for processing (1)
  • app/store/chat.ts (2 hunks)
🧰 Additional context used

Comment on lines 739 to 758
if (typeof message !== "string") {
return false;
}
if (message.startsWith("```") && message.endsWith("```")) {
const codeBlockContent = message.slice(3, -3).trim();
const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
try {
// 返回 json 格式消息,含 error.message 字段,判定为错误回复,否则为正常回复
const jsonObject = JSON.parse(jsonString);
if (jsonObject?.error?.message) {
return false;
}
return true;
} catch (e) {
console.log("Invalid JSON format.");
// 非 json 格式,大概率是正常回复
return true;
}
}
return true;
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

Enhance robustness of isValidMessage function

The isValidMessage function is a good addition to validate messages before processing. However, consider the following improvements:

  1. Check if the code block starts with "```json" before attempting to parse it as JSON.
  2. Handle different types of code blocks, not just JSON.
  3. Improve error handling to be more specific about what went wrong.

Here's a suggested refactor:

 function isValidMessage(message: any): boolean {
   if (typeof message !== "string") {
     return false;
   }
   if (message.startsWith("```") && message.endsWith("```")) {
     const codeBlockContent = message.slice(3, -3).trim();
-    const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
+    if (codeBlockContent.toLowerCase().startsWith('json')) {
+      const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
+      try {
+        const jsonObject = JSON.parse(jsonString);
+        return !jsonObject?.error?.message;
+      } catch (e) {
+        console.log("Invalid JSON format:", e.message);
+        return false;
+      }
+    }
+    // Non-JSON code blocks are considered valid
+    return true;
   }
-    try {
-      // 返回 json 格式消息,含 error.message 字段,判定为错误回复,否则为正常回复
-      const jsonObject = JSON.parse(jsonString);
-      if (jsonObject?.error?.message) {
-        return false;
-      }
-      return true;
-    } catch (e) {
-      console.log("Invalid JSON format.");
-      // 非 json 格式,大概率是正常回复
-      return true;
-    }
-  }
   return true;
 }

This refactor:

  • Only attempts to parse JSON if the code block explicitly starts with "json".
  • Treats non-JSON code blocks as valid messages.
  • Improves error logging for invalid JSON.
  • Simplifies the overall logic.

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: 1

🧹 Outside diff range and nitpick comments (5)
test/isValidMessage.test.ts (3)

1-22: Good implementation, but consider some improvements

The isValidMessage function is well-structured and handles various scenarios effectively. However, there are a few areas for potential improvement:

  1. The input parameter type any could be more specific. Consider using unknown for better type safety.
  2. The function returns true for non-JSON content, which might not always be desirable. Consider adding a parameter to control this behavior.
  3. The error logging could be more informative. Consider including the actual error message.

Here's a suggested refactoring:

function isValidMessage(message: unknown, allowNonJson: boolean = true): boolean {
    if (typeof message !== "string") {
        return false;
    }
    if (message.startsWith("```") && message.endsWith("```")) {
        const codeBlockContent = message.slice(3, -3).trim();
        const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
        try {
            const jsonObject = JSON.parse(jsonString);
            if (jsonObject?.error === true || jsonObject?.error?.message) {
                return false;
            }
            return true;
        } catch (e) {
            console.error(`Invalid JSON format: ${(e as Error).message}`);
            return allowNonJson;
        }
    }
    return allowNonJson;
}

This refactoring addresses the mentioned issues and provides more flexibility in handling non-JSON content.


24-96: Comprehensive test suite with room for enhancement

The test suite is well-structured and covers a good range of scenarios, which is commendable. To further improve it:

  1. Consider adding more edge cases, such as:
    • Empty string input
    • Malformed JSON
    • Non-string inputs (e.g., numbers, objects)
  2. Make test descriptions more specific about what they're testing. For example, instead of "error msg no.1", use something like "should return false for JSON with error field set to true".
  3. Consider grouping related tests using describe blocks for better organization.

Here's an example of how you could structure a new test case:

test("should return false for malformed JSON", () => {
    const message = "```{\"error\": true,```";
    expect(isValidMessage(message)).toBe(false);
});

Adding such cases would increase the robustness of your test suite.


1-96: Overall, good implementation with room for refinement

The isValidMessage function and its accompanying test suite form a solid foundation for message validation in your project. The function effectively handles various scenarios, particularly focusing on identifying error responses in JSON format. The test suite provides good coverage of different cases.

To further enhance this implementation:

  1. Consider the suggested refactoring of the isValidMessage function to improve type safety and flexibility.
  2. Expand the test suite to cover more edge cases and improve test descriptions.
  3. Group related tests for better organization.

These improvements will contribute to making your code more robust and maintainable.

As you continue to develop this feature, consider how it integrates with the larger error handling strategy of your application. You might want to create a more comprehensive error handling module that includes this function as part of a broader set of utilities for managing and responding to various types of errors consistently across your application.

app/store/chat.ts (2)

726-728: Approve changes with a minor suggestion

The addition of the isValidMessage check is a good practice to ensure that only valid messages are processed. This improves the robustness of the code by filtering out potentially problematic messages.

Consider moving the isValidMessage function definition before its usage to improve code readability and maintainability. This would make the code easier to follow and understand.


Line range hint 726-758: Overall improvement in message validation with room for refinement

The changes introduced in this PR enhance the robustness of the chat system by adding message validation checks. The new isValidMessage function and its integration into the summarizeSession function are positive additions that help filter out potentially problematic messages.

However, there are opportunities for further improvement:

  1. The placement of the isValidMessage function could be optimized for better code organization.
  2. The error handling and validation logic in isValidMessage could be more comprehensive and specific.

These refinements would further enhance the maintainability and reliability of the code.

Consider creating a separate module for message validation functions if similar checks are needed elsewhere in the codebase. This would improve code organization and reusability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7d7ca64 and dd793e0.

📒 Files selected for processing (2)
  • app/store/chat.ts (2 hunks)
  • test/isValidMessage.test.ts (1 hunks)
🧰 Additional context used

Comment on lines 739 to 758
if (typeof message !== "string") {
return false;
}
if (message.startsWith("```") && message.endsWith("```")) {
const codeBlockContent = message.slice(3, -3).trim();
const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
try {
// 返回 json 格式消息,error 字段为 true 或者包含 error.message 字段,判定为错误回复,否则为正常回复
const jsonObject = JSON.parse(jsonString);
if (jsonObject?.error == true || jsonObject?.error?.message) {
return false;
}
return true;
} catch (e) {
console.log("Invalid JSON format.");
// 非 json 格式,通常可认为是正常回复
return true;
}
}
return true;
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

Enhance robustness of isValidMessage function

The isValidMessage function is a good addition to validate messages. However, consider the following improvements:

  1. Handle different types of code blocks, not just JSON.
  2. Improve error handling to be more specific about what went wrong.
  3. Consider additional validation for non-JSON messages.

Here's a suggested refactor:

 function isValidMessage(message: any): boolean {
   if (typeof message !== "string") {
     return false;
   }
   if (message.startsWith("```") && message.endsWith("```")) {
     const codeBlockContent = message.slice(3, -3).trim();
-    const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
+    if (codeBlockContent.toLowerCase().startsWith('json')) {
+      const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
+      try {
+        const jsonObject = JSON.parse(jsonString);
+        return !jsonObject?.error?.message;
+      } catch (e) {
+        console.log("Invalid JSON format:", e.message);
+        return false;
+      }
+    }
+    // Non-JSON code blocks are considered valid
+    return true;
   }
-    try {
-      // 返回 json 格式消息,error 字段为 true 或者包含 error.message 字段,判定为错误回复,否则为正常回复
-      const jsonObject = JSON.parse(jsonString);
-      if (jsonObject?.error == true || jsonObject?.error?.message) {
-        return false;
-      }
-      return true;
-    } catch (e) {
-      console.log("Invalid JSON format.");
-      // 非 json 格式,通常可认为是正常回复
-      return true;
-    }
-  }
   return true;
 }

This refactor:

  • Only attempts to parse JSON if the code block explicitly starts with "json".
  • Treats non-JSON code blocks as valid messages.
  • Improves error logging for invalid JSON.
  • Simplifies the overall logic.
📝 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
if (typeof message !== "string") {
return false;
}
if (message.startsWith("```") && message.endsWith("```")) {
const codeBlockContent = message.slice(3, -3).trim();
const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
try {
// 返回 json 格式消息,error 字段为 true 或者包含 error.message 字段,判定为错误回复,否则为正常回复
const jsonObject = JSON.parse(jsonString);
if (jsonObject?.error == true || jsonObject?.error?.message) {
return false;
}
return true;
} catch (e) {
console.log("Invalid JSON format.");
// 非 json 格式,通常可认为是正常回复
return true;
}
}
return true;
function isValidMessage(message: any): boolean {
if (typeof message !== "string") {
return false;
}
if (message.startsWith("```") && message.endsWith("```")) {
const codeBlockContent = message.slice(3, -3).trim();
if (codeBlockContent.toLowerCase().startsWith('json')) {
const jsonString = codeBlockContent.replace(/^json\s*/i, '').trim();
try {
const jsonObject = JSON.parse(jsonString);
return !jsonObject?.error?.message;
} catch (e) {
console.log("Invalid JSON format:", e.message);
return false;
}
}
// Non-JSON code blocks are considered valid
return true;
}
return true;
}

@@ -739,19 +739,20 @@ export const useChatStore = createPersistStore(
if (typeof message !== "string") {
return false;
}
message = message.trim();
Copy link
Member

Choose a reason for hiding this comment

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

应该在此class外将isValidMessage 导出
然后在对应的test 文件引入,而不是复制一份

@@ -0,0 +1,161 @@
function isValidMessage(message: any): boolean {
Copy link
Member

Choose a reason for hiding this comment

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

import { isValidMessage } from @/app/store/chat

@Dogtiti
Copy link
Member

Dogtiti commented Nov 4, 2024

#5759

@Dogtiti Dogtiti closed this Nov 4, 2024
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