Skip to content

2 way sync of rules and prompt file#309

Merged
elie222 merged 9 commits intomainfrom
generate-prompt-from-rules
Jan 16, 2025
Merged

2 way sync of rules and prompt file#309
elie222 merged 9 commits intomainfrom
generate-prompt-from-rules

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 16, 2025

when rules are manually updated we now update the prompt file too

Summary by CodeRabbit

  • Code Refactoring

    • Relocated deleteRuleAction from ai-rule.ts to rule.ts
    • Updated import statements in Rules.tsx to reflect the new action location
  • New Features

    • Added comprehensive test suite for rule prompt generation
    • Introduced new functions for generating prompts on rule updates and deletions
    • Added functionality to delete rules with appropriate user permissions and prompt updates
  • Improvements

    • Enhanced rule management with more robust prompt handling
    • Added more detailed rule retrieval and processing in actions

@vercel
Copy link

vercel bot commented Jan 16, 2025

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

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Jan 16, 2025 10:42am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request involves modifications to the rule management functionality across several files. The deleteRuleAction function has been moved from ai-rule.ts to rule.ts, and a new deleteRuleAction has been added in rule.ts to facilitate rule deletion. Additionally, new functions for generating prompts related to rule updates and deletions have been introduced. A comprehensive test suite for prompt generation has also been added, enhancing the overall functionality and organization of rule management.

Changes

File Change Summary
apps/web/app/(app)/automation/Rules.tsx Updated import for deleteRuleAction from @/utils/actions/rule instead of @/utils/actions/ai-rule
apps/web/utils/actions/ai-rule.ts Removed deleteRuleAction function
apps/web/utils/actions/rule.ts Added deleteRuleAction, updatePromptFileOnUpdate, and updateUserPrompt functions; enhanced rule management methods
apps/web/utils/ai/rule/create-prompt-from-rule.ts New file with RuleWithRelations type and createPromptFromRule function
apps/web/utils/ai/rule/create-prompt-from-rule.test.ts Added comprehensive test suite for prompt generation
apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts New file with generatePromptOnDeleteRule function
apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts New file with generatePromptOnUpdateRule function

Possibly related PRs

Poem

🐰 A Rabbit's Rule Refrain 🐰

In code's wild warren, rules take flight,
Prompts dancing with algorithmic might,
Delete, update, with grace so keen,
Our rule management now pristine!
Hop, hop, hooray for clean design! 🎉


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba5a75b and e88f47d.

📒 Files selected for processing (3)
  • apps/web/utils/actions/rule.ts (9 hunks)
  • apps/web/utils/ai/rule/create-prompt-from-rule.ts (1 hunks)
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts (1 hunks)

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
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: 7

🧹 Nitpick comments (5)
apps/web/utils/actions/rule.ts (2)

13-13: Organize and Optimize Imports

The imports in this file can be better organized for readability. Group related imports together and remove any unused imports to keep the code clean and maintainable.


258-268: Return Consistent Error Responses

In deleteRuleAction, when a rule is not found or the user lacks permission, the function either returns nothing or an error object. For consistency, always return a standardized error response.

Modify the code:

if (!rule) return { error: "Rule not found" };
if (rule.userId !== session.user.id) return { error: "Unauthorized access" };
apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts (1)

31-52: Review Clarity of AI Instructions

The instructions provided to the AI assistant are clear but can be refined for brevity.

For example, combine similar steps or remove unnecessary details to make the instructions more concise.

apps/web/utils/ai/rule/create-prompt-from-rule.ts (1)

9-35: Consider adding input validation for rule conditions.

While the condition handling is comprehensive, consider adding validation for potentially problematic inputs:

  • Empty strings in conditions
  • Special characters that might need escaping
  • Maximum length limits for conditions
 if (rule.from) conditions.push(`from "${rule.from}"`);
+if (rule.from?.trim()) conditions.push(`from "${escapeString(rule.from)}"`);

 function escapeString(str: string): string {
   return str.replace(/["\\]/g, '\\$&');
 }
apps/web/utils/ai/rule/create-prompt-from-rule.test.ts (1)

5-212: Add test cases for edge cases and error scenarios.

The test suite is comprehensive but could be enhanced with additional test cases:

  • Empty or whitespace-only strings in conditions
  • Very long strings in conditions
  • Invalid URLs in webhook actions
  • Malformed templates in reply actions

Example test case:

it("handles empty and whitespace-only conditions", () => {
  const rule = {
    from: "   ",
    subject: "",
    actions: [{ type: "ARCHIVE" }] as Action[],
  } as Rule & { actions: Action[] };

  expect(createPromptFromRule(rule)).toBe("For all emails, archive");
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 67a5a72 and ba5a75b.

📒 Files selected for processing (7)
  • apps/web/app/(app)/automation/Rules.tsx (1 hunks)
  • apps/web/utils/actions/ai-rule.ts (0 hunks)
  • apps/web/utils/actions/rule.ts (9 hunks)
  • apps/web/utils/ai/rule/create-prompt-from-rule.test.ts (1 hunks)
  • apps/web/utils/ai/rule/create-prompt-from-rule.ts (1 hunks)
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts (1 hunks)
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/utils/actions/ai-rule.ts
🔇 Additional comments (10)
apps/web/utils/actions/rule.ts (4)

122-122: Ensure Correct Retrieval of Current Rule

When fetching the currentRule in updateRuleAction, confirm that the include clause retrieves all necessary related data, as it is crucial for accurate prompt updates later in the function.


134-134: Validate Updated Rule Data

After the Prisma transaction, only the first element is assigned to updatedRule. Ensure that this element indeed contains the updated rule with all expected relations included.

Double-check the transaction array to confirm that updatedRule is correctly obtained.


286-306: Handle Potential Errors in Prompt Update

After generating the updatedPrompt, there is no error handling for the subsequent database update. Failure to update the user prompt could go unnoticed.

Implement error handling:

try {
  await prisma.user.update({
    where: { id: session.user.id },
    data: { rulesPrompt: updatedPrompt },
  });
} catch (error) {
  // Handle or log the error appropriately
}

87-91: Handle Errors When Updating User Prompt

In createRuleAction, the asynchronous call to updateUserPrompt lacks error handling. If updating the user's prompt fails, the error will go unnoticed, potentially causing inconsistencies.

Consider adding a try-catch block around updateUserPrompt to handle any exceptions:

try {
  await updateUserPrompt(session.user.id, prompt);
} catch (error) {
  // Handle or log the error appropriately
}
apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts (2)

28-30: Handle Empty Prompt Scenarios

When existingPrompt or deletedRulePrompt is empty, the function returns an empty string. This could lead to unintended behavior if the calling code doesn't anticipate it.

Consider throwing an error or handling this case explicitly. Ensure the calling function can handle an empty string appropriately.


56-65: Add Error Handling for AI Response

The function assumes that chatCompletionObject will return a valid response. If the AI service fails or returns an unexpected format, it might cause issues.

Implement error handling to manage exceptions or invalid responses from the AI service.

apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts (2)

31-33: Handle Missing Prompts Appropriately

Similar to the delete rule function, ensure that when existingPrompt or updatedRulePrompt is missing, the function handles it appropriately.

Decide whether to throw an error or handle the empty return value in the calling code.


60-69: Include Error Handling for AI Service Call

As with the other AI-related function, add error handling around the chatCompletionObject call to catch any exceptions or invalid responses.

Example:

let parsedResponse;
try {
  const aiResponse = await chatCompletionObject({ /* params */ });
  parsedResponse = aiResponse.object;
} catch (error) {
  // Handle or log the error appropriately
}
apps/web/utils/ai/rule/create-prompt-from-rule.ts (1)

1-7: LGTM! Well-structured type definition.

The RuleWithRelations type properly extends the base Rule type with necessary relationships for actions, category filters, and groups.

apps/web/app/(app)/automation/Rules.tsx (1)

40-40: LGTM! Correct import path update.

The import path for deleteRuleAction has been properly updated to reflect the new location of the function.

Comment on lines +205 to +207
// update prompt file
await updatePromptFileOnUpdate(session.user.id, currentRule, updatedRule);

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 Error Handling for Prompt Update

In updateRuleAction, the call to updatePromptFileOnUpdate doesn't handle potential errors. If the prompt update fails, this could lead to inconsistent state without any notification.

Implement error handling:

try {
  await updatePromptFileOnUpdate(session.user.id, currentRule, updatedRule);
} catch (error) {
  // Handle or log the error appropriately
}

Comment on lines +235 to +252
const currentRule = await prisma.rule.findUnique({
where: { id: body.id, userId: session.user.id },
include: { actions: true, categoryFilters: true, group: true },
});
if (!currentRule) return { error: "Rule not found" };

const updatedRule = await prisma.rule.update({
where: { id: body.id, userId: session.user.id },
data: { instructions: body.instructions },
include: { actions: true, categoryFilters: true, group: true },
});

// update prompt file
await updatePromptFileOnUpdate(session.user.id, currentRule, updatedRule);

revalidatePath(`/automation/rule/${body.id}`);
revalidatePath("/automation");
},
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

Ensure Consistent Return Values

The updateRuleInstructionsAction function lacks a return statement. For consistency and to facilitate error handling on the client side, consider returning a response.

Add a return statement at the end of the function:

return { success: true };

@elie222 elie222 merged commit 5efd582 into main Jan 16, 2025
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 19, 2025
@coderabbitai coderabbitai bot mentioned this pull request Feb 25, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 5, 2025
@elie222 elie222 deleted the generate-prompt-from-rules branch December 18, 2025 23:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments