Skip to content

Conversation

@hasinaxp
Copy link
Contributor

@hasinaxp hasinaxp commented May 5, 2025

Summary by CodeRabbit

  • New Features

    • Added a configuration option to email actions allowing control over whether the bot's response is sent to the user after an email is sent.
  • Tests

    • Introduced and updated tests to ensure correct behavior when the new email action configuration is enabled or disabled.

@coderabbitai
Copy link

coderabbitai bot commented May 5, 2025

Walkthrough

A new configuration parameter, dispatch_bot_response, has been introduced to control whether the bot's response message is dispatched to the user after an email action is executed. This parameter, defaulting to True, has been added to the relevant data models, configuration classes, and processing logic. The email action execution flow now conditionally dispatches the bot response based on this flag. Tests have been updated and expanded to cover scenarios where this flag is both True and False, ensuring the feature works as intended.

Changes

File(s) Change Summary
kairon/actions/definitions/email.py Added dispatch_bot_response parameter to control bot response dispatching; moved response sending inside a guarded block based on this flag.
kairon/shared/actions/data_objects.py Added dispatch_bot_response Boolean field (default True) to EmailActionConfig.
kairon/shared/data/data_models.py Added dispatch_bot_response Boolean field (default True) to EmailActionRequest model.
kairon/shared/data/processor.py Updated edit_email_action to set dispatch_bot_response attribute from input action dict.
tests/integration_test/action_service_test.py Added test_email_action_execution_dispaatch_false to verify behavior when dispatch_bot_response is False.
tests/integration_test/services_test.py Updated email action config test data to include dispatch_bot_response: True in multiple configurations.
tests/unit_test/data_processor/data_processor_test.py Added test_add_email_action_dispatch_false and updated existing tests to explicitly set and check dispatch_bot_response field in various scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Bot
    participant EmailAction
    participant Dispatcher

    User->>Bot: Triggers email action
    Bot->>EmailAction: Execute email action
    EmailAction->>EmailAction: Send email (SMTP)
    alt dispatch_bot_response == True
        EmailAction->>Dispatcher: utter_message(bot_response)
    else dispatch_bot_response == False
        EmailAction-->>Dispatcher: (No message dispatched)
    end
    EmailAction-->>Bot: Return result
    Bot-->>User: (Depends on dispatch_bot_response)
Loading

Suggested reviewers

  • hiteshghuge

Poem

In the warren of code, a new flag appears,
To hush the bot’s reply or bring user cheers.
With tests all a-flutter, both false and true,
The email hops forth, with responses anew.
Dispatch or be silent, the bunny now knows—
For every email action, control clearly shows!
🐇📧

✨ 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.

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.

Copy link

@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

🧹 Nitpick comments (7)
tests/integration_test/services_test.py (3)

23340-23340: Ensure consistency in key quoting
The addition of 'dispatch_bot_response': True correctly aligns the test with the new default flag behavior. For readability and consistency with the surrounding JSON‐style keys, consider using double quotes ("dispatch_bot_response") instead of single quotes.


23360-23360: Ensure consistency in key quoting
The addition of 'dispatch_bot_response': True correctly aligns the test with the new default flag behavior. For readability and consistency with the surrounding JSON‐style keys, consider using double quotes ("dispatch_bot_response") instead of single quotes.


23380-23380: Ensure consistency in key quoting
The addition of 'dispatch_bot_response': True correctly aligns the test with the new default flag behavior. For readability and consistency with the surrounding JSON‐style keys, consider using double quotes ("dispatch_bot_response") instead of single quotes.

kairon/actions/definitions/email.py (1)

44-52: Consider updating docstring to reflect new behavior.

The docstring could be updated to mention the new dispatch_bot_response parameter and its purpose, explaining that the bot response dispatch is now optional based on configuration.

@param dispatcher: Client to send messages back to the user.
@param tracker: Tracker object to retrieve slots, events, messages and other contextual information.
@param domain: Bot domain
+Note: Bot response dispatch to the user can be controlled via the `dispatch_bot_response` configuration parameter.
:return: Dict containing slot name as keys and their values.
tests/integration_test/action_service_test.py (3)

6156-6156: Fix typo in function name

There's a typo in the function name: "dispaatch" should be "dispatch".

-def test_email_action_execution_dispaatch_false(mock_smtp, mock_action_config, mock_action):
+def test_email_action_execution_dispatch_false(mock_smtp, mock_action_config, mock_action):

6281-6281: Avoid Yoda conditions

The code uses Yoda conditions ({} == kwargs) which are less readable. It's better to put the variable first in the comparison.

-    assert {} == kwargs
+    assert kwargs == {}

Also applies to: 6288-6288, 6296-6296

🧰 Tools
🪛 Ruff (0.8.2)

6281-6281: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)


6153-6304: Consider extracting duplicate SMTP assertion code

This test contains nearly identical SMTP assertion code as other email action tests. Consider extracting these assertions into a helper method to reduce code duplication.

You could create a helper method like:

def assert_smtp_calls(mock_smtp, action_config, expected_subject=None):
    """Assert that SMTP calls were made correctly with the given config."""
    # Assert connection
    name, args, kwargs = mock_smtp.method_calls.pop(0)
    assert name == '().connect'
    assert kwargs == {}
    host, port = args
    assert host == action_config.smtp_url
    assert port == action_config.smtp_port
    
    # Assert login
    name, args, kwargs = mock_smtp.method_calls.pop(0)
    assert name == '().login'
    assert kwargs == {}
    from_email, password = args
    assert from_email == action_config.from_email.value
    assert password == action_config.smtp_password.value
    
    # Assert sendmail
    name, args, kwargs = mock_smtp.method_calls.pop(0)
    assert name == '().sendmail'
    assert kwargs == {}
    assert args[0] == action_config.from_email.value
    assert args[1] == action_config.to_email.value
    assert str(args[2]).__contains__(action_config.subject)
    assert str(args[2]).__contains__("Content-Type: text/html")
    if expected_subject:
        assert str(args[2]).__contains__(f"Subject: {expected_subject}")

Then use it in your tests:

assert_smtp_calls(mock_smtp, action_config, expected_subject="default test")
🧰 Tools
🪛 Ruff (0.8.2)

6157-6157: Use a context manager for opening files

(SIM115)


6159-6159: Use a context manager for opening files

(SIM115)


6161-6161: Use a context manager for opening files

(SIM115)


6163-6163: Use a context manager for opening files

(SIM115)


6281-6281: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)


6288-6288: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)


6296-6296: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d30d7ce and 1eb97b5.

📒 Files selected for processing (7)
  • kairon/actions/definitions/email.py (2 hunks)
  • kairon/shared/actions/data_objects.py (1 hunks)
  • kairon/shared/data/data_models.py (1 hunks)
  • kairon/shared/data/processor.py (1 hunks)
  • tests/integration_test/action_service_test.py (1 hunks)
  • tests/integration_test/services_test.py (3 hunks)
  • tests/unit_test/data_processor/data_processor_test.py (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit_test/data_processor/data_processor_test.py (4)
tests/unit_test/api/api_processor_test.py (1)
  • mock_smtp (1189-1190)
tests/integration_test/services_test.py (1)
  • mock_smtp (115-116)
kairon/shared/data/processor.py (2)
  • add_email_action (7085-7107)
  • edit_email_action (7109-7156)
kairon/shared/actions/data_objects.py (1)
  • EmailActionConfig (437-493)
🪛 Ruff (0.8.2)
tests/integration_test/action_service_test.py

6157-6157: Use a context manager for opening files

(SIM115)


6159-6159: Use a context manager for opening files

(SIM115)


6161-6161: Use a context manager for opening files

(SIM115)


6163-6163: Use a context manager for opening files

(SIM115)


6281-6281: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)


6288-6288: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)


6296-6296: Yoda condition detected

Rewrite as kwargs == {}

(SIM300)

tests/unit_test/data_processor/data_processor_test.py

16056-16056: Local variable mock_smtp is assigned to but never used

Remove assignment to unused variable mock_smtp

(F841)


16073-16073: Local variable mock_smtp is assigned to but never used

Remove assignment to unused variable mock_smtp

(F841)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Python CI
  • GitHub Check: Analyze (python)
🔇 Additional comments (15)
kairon/shared/actions/data_objects.py (1)

447-447: Clean implementation of the new configuration parameter.

The addition of the dispatch_bot_response boolean field with a default value of True aligns perfectly with the PR objective of making bot response dispatch optional for email actions. The default value ensures backward compatibility with existing behavior.

kairon/shared/data/data_models.py (1)

1004-1004: Good consistency in implementation across models.

The dispatch_bot_response field addition in the EmailActionRequest Pydantic model mirrors the same field added to the EmailActionConfig class, ensuring consistency across the data models and request handling. The default value of True maintains backward compatibility.

kairon/shared/data/processor.py (1)

7152-7152: Support added for controlling bot response dispatching in email actions.

This change assigns the dispatch_bot_response flag from the input parameters to the email action configuration, allowing users to control whether bot responses are sent to users after email actions are executed.

kairon/actions/definitions/email.py (2)

57-57: Clean implementation of new configuration parameter.

The addition of dispatch_bot_response with a default value of True ensures backward compatibility with existing configurations that don't have this parameter defined. The parameter name is descriptive and follows the naming conventions in the codebase.


91-92: Good implementation of conditional bot response dispatch.

The conditional check correctly implements the feature described in the PR title, making the bot response dispatch optional based on configuration. The code is clearly structured with proper indentation.

tests/integration_test/action_service_test.py (2)

6166-6180: The action configuration looks good

The test correctly sets up the EmailActionConfig with dispatch_bot_response=False, which is the key parameter being tested in this function.


6270-6275: Good assertions for testing non-dispatch behavior

These assertions correctly verify that when dispatch_bot_response=False:

  1. No bot responses are returned (empty responses list)
  2. The slot is still updated with the action response

This confirms the expected behavior that the action executes but doesn't dispatch a response to the user.

tests/unit_test/data_processor/data_processor_test.py (8)

16053-16053: Good addition of the new dispatch_bot_response parameter.

Adding the dispatch_bot_response parameter with default value True aligns with the implementation in the EmailActionConfig model.


16059-16075: Excellent test coverage for the new feature!

This test properly verifies adding an email action with dispatch_bot_response set to False. It appropriately tests the new functionality and includes proper cleanup by deleting the test action afterward.

The mock_smtp variables in these tests are flagged by static analysis but are correctly used as part of the patch context manager pattern, which is a standard testing approach.

🧰 Tools
🪛 Ruff (0.8.2)

16073-16073: Local variable mock_smtp is assigned to but never used

Remove assignment to unused variable mock_smtp

(F841)


16088-16089: Good parametrization.

Adding the dispatch_bot_response parameter to this custom text test case ensures consistent test coverage.


16128-16129: Good inclusion of the parameter in additional test case.

Consistently adding the parameter across all relevant test cases ensures thorough coverage.


16190-16191: Proper test coverage continued.

Maintaining consistent test patterns with the new parameter across all email action tests.


16209-16210: Appropriate parameter addition for slot-based test.

The dispatch_bot_response parameter is correctly added to this slot-based test scenario.


16228-16228: Well-structured test for both True and False values!

This test effectively covers both values of the dispatch_bot_response parameter:

  1. Initially set to False for the first edit test
  2. Then explicitly updated to True for the second edit test with custom text slot

This approach provides good coverage of the editing functionality with the new parameter.

Also applies to: 16235-16235


16250-16250: Consistent parameter inclusion.

The dispatch_bot_response parameter is consistently added throughout all relevant test cases, ensuring thorough test coverage.

Comment on lines +6157 to +6164
Utility.email_conf['email']['templates']['conversation'] = open('template/emails/conversation.html',
'rb').read().decode()
Utility.email_conf['email']['templates']['bot_msg_conversation'] = open(
'template/emails/bot_msg_conversation.html', 'rb').read().decode()
Utility.email_conf['email']['templates']['user_msg_conversation'] = open(
'template/emails/user_msg_conversation.html', 'rb').read().decode()
Utility.email_conf['email']['templates']['button_template'] = open('template/emails/button.html',
'rb').read().decode()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use context managers for file operations

Opening files without context managers can lead to resource leaks if exceptions occur. Use with statements to ensure files are properly closed.

-    Utility.email_conf['email']['templates']['conversation'] = open('template/emails/conversation.html',
-                                                                    'rb').read().decode()
-    Utility.email_conf['email']['templates']['bot_msg_conversation'] = open(
-        'template/emails/bot_msg_conversation.html', 'rb').read().decode()
-    Utility.email_conf['email']['templates']['user_msg_conversation'] = open(
-        'template/emails/user_msg_conversation.html', 'rb').read().decode()
-    Utility.email_conf['email']['templates']['button_template'] = open('template/emails/button.html',
-                                                                       'rb').read().decode()
+    with open('template/emails/conversation.html', 'rb') as f:
+        Utility.email_conf['email']['templates']['conversation'] = f.read().decode()
+    with open('template/emails/bot_msg_conversation.html', 'rb') as f:
+        Utility.email_conf['email']['templates']['bot_msg_conversation'] = f.read().decode()
+    with open('template/emails/user_msg_conversation.html', 'rb') as f:
+        Utility.email_conf['email']['templates']['user_msg_conversation'] = f.read().decode()
+    with open('template/emails/button.html', 'rb') as f:
+        Utility.email_conf['email']['templates']['button_template'] = f.read().decode()
📝 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
Utility.email_conf['email']['templates']['conversation'] = open('template/emails/conversation.html',
'rb').read().decode()
Utility.email_conf['email']['templates']['bot_msg_conversation'] = open(
'template/emails/bot_msg_conversation.html', 'rb').read().decode()
Utility.email_conf['email']['templates']['user_msg_conversation'] = open(
'template/emails/user_msg_conversation.html', 'rb').read().decode()
Utility.email_conf['email']['templates']['button_template'] = open('template/emails/button.html',
'rb').read().decode()
with open('template/emails/conversation.html', 'rb') as f:
Utility.email_conf['email']['templates']['conversation'] = f.read().decode()
with open('template/emails/bot_msg_conversation.html', 'rb') as f:
Utility.email_conf['email']['templates']['bot_msg_conversation'] = f.read().decode()
with open('template/emails/user_msg_conversation.html', 'rb') as f:
Utility.email_conf['email']['templates']['user_msg_conversation'] = f.read().decode()
with open('template/emails/button.html', 'rb') as f:
Utility.email_conf['email']['templates']['button_template'] = f.read().decode()
🧰 Tools
🪛 Ruff (0.8.2)

6157-6157: Use a context manager for opening files

(SIM115)


6159-6159: Use a context manager for opening files

(SIM115)


6161-6161: Use a context manager for opening files

(SIM115)


6163-6163: Use a context manager for opening files

(SIM115)

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