Skip to content

feat: add contextVar regex validation #921

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

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

yassinedorbozgithub
Copy link
Collaborator

@yassinedorbozgithub yassinedorbozgithub commented Apr 13, 2025

Motivation:

The main motivation is to add an extra regex validation before updating contextVars (permanent, and not permanent).
This added feature will give us the possibility to use multiple contextVars in the same block without value interference.

(NB: this update suppose that the regex for all the contextVars used in the same block are unique)

Fixes #917

Screenshots:

image
image

Checklist:

  • I have performed a self-review of my own code
  • I have added unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Introduced regex pattern support for context variable configurations. Users can now specify a custom regex pattern when creating or updating context variables.
    • Expanded the context variable form with a dedicated input field that validates the regex format.
    • Enhanced the display in context variable listings with a new column showing the configured regex pattern.
  • Refactor

    • Improved validation logic ensures that only context variable values matching the defined patterns are accepted.
    • Updated method signatures to accommodate potential undefined values in context variable retrieval.

@yassinedorbozgithub yassinedorbozgithub added the enhancement New feature or request label Apr 13, 2025
@yassinedorbozgithub yassinedorbozgithub self-assigned this Apr 13, 2025
Copy link

coderabbitai bot commented Apr 13, 2025

Walkthrough

The changes introduce a new optional property, pattern, across backend and frontend components handling context variables. The updates include modifications to DTOs, schemas, and tests to incorporate a default regex pattern, as well as service logic enhancements that validate context variable values against the specified pattern. Additionally, corresponding UI components now support regex input and display, and minor updates such as revised copyright years have been applied.

Changes

File(s) Change Summary
api/src/chat/controllers/context-var.controller.spec.ts
api/src/utils/test/fixtures/contextvar.ts
Added pattern property with a default value /.+/ in test fixtures and DTO objects used in test cases.
api/src/chat/dto/context-var.dto.ts
api/src/chat/schemas/context-var.schema.ts
frontend/src/types/context-var.types.ts
Added new optional pattern property for context variable validation; updated copyright year.
api/src/chat/services/context-var.service.ts Updated return type of getContextVarsByBlock method to allow undefined values.
api/src/chat/services/conversation.service.ts Enhanced context variable logic to validate input using regex pattern; uses structured pattern check and logs warnings for non-matching values; updated logger usage.
frontend/src/components/context-vars/ContextVarForm.tsx
frontend/src/components/visual-editor/form/inputs/triggers/PatternInput.tsx
Added new regex input field with validation; exported isRegex function for reuse.
frontend/src/components/context-vars/index.tsx Added a new column to render the context variable’s regex pattern using a Chip component and updated import statements.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CS as ConversationService
    participant DB as ContextVar Repository
    participant L as Logger

    U->>CS: Submit user input with value
    CS->>DB: Retrieve context variable configuration
    CS->>CS: Validate input against `pattern`
    alt Value matches pattern
       CS->>CS: Update profile and conversation contexts
    else Value does not match pattern
       CS->>L: Log warning and skip update
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Add support for regex/validation rules for context variables (#917)

Poem

I'm a rabbit coding in a whimsical glade,
Where regex patterns in the code parade.
Each carrot of change makes my hops so light,
Validating context vars both day and night.
Hurray for code that’s clever and bright! 🥕✨


📜 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 9f797ac and 0253d33.

📒 Files selected for processing (1)
  • frontend/src/components/context-vars/ContextVarForm.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/context-vars/ContextVarForm.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Frontend Tests
  • GitHub Check: API-Tests

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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: 3

🧹 Nitpick comments (4)
api/src/chat/services/conversation.service.ts (2)

119-120: Use template literal conversion with caution

Converting contextValue to a string using template literals (${contextValue}) works for simple values but may produce unexpected results with complex objects or arrays.

Consider adding a more robust type check or conversion for non-string values:

- const isValidContextValue = new RegExp(pattern.slice(1, -1)).test(
-   `${contextValue}`,
- );
+ const stringValue = typeof contextValue === 'object' ? 
+   JSON.stringify(contextValue) : `${contextValue}`;
+ const isValidContextValue = new RegExp(pattern.slice(1, -1)).test(stringValue);

118-119: Add a default pattern handling

The current code uses an empty string as the default pattern, which will match anything when converted to a RegExp. This might lead to unexpected behavior if a pattern is missing.

- const { permanent, pattern = '' } = context_var || {};
+ const { permanent, pattern = '/.+/' } = context_var || {};
frontend/src/components/context-vars/ContextVarForm.tsx (2)

177-181: Add informative helper text for regex patterns

The regex input would benefit from guidance on the expected format and purpose of the regex pattern.

helperText={errors.pattern 
  ? errors.pattern.message 
- : null}
+ : t("help.regex_pattern_for_context_vars")}

Consider adding a translation key with helpful information about using regex patterns for context variables.


158-160: Consider more explicit empty pattern handling

The current code treats an empty pattern as valid, which will match any string. This might be unintended behavior.

- if (pattern.slice(1, -1) === "") {
-   return true;
- }
+ if (pattern.slice(1, -1) === "") {
+   return t("message.empty_regex_will_match_anything");
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dadb263 and 06b4c1a.

📒 Files selected for processing (10)
  • api/src/chat/controllers/context-var.controller.spec.ts (1 hunks)
  • api/src/chat/dto/context-var.dto.ts (2 hunks)
  • api/src/chat/schemas/context-var.schema.ts (3 hunks)
  • api/src/chat/services/context-var.service.ts (2 hunks)
  • api/src/chat/services/conversation.service.ts (2 hunks)
  • api/src/utils/test/fixtures/contextvar.ts (1 hunks)
  • frontend/src/components/context-vars/ContextVarForm.tsx (5 hunks)
  • frontend/src/components/context-vars/index.tsx (2 hunks)
  • frontend/src/components/visual-editor/form/inputs/triggers/PatternInput.tsx (1 hunks)
  • frontend/src/types/context-var.types.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
frontend/src/components/visual-editor/form/inputs/triggers/PatternInput.tsx (1)
frontend/src/types/block.types.ts (1)
  • Pattern (77-77)
api/src/chat/schemas/context-var.schema.ts (2)
api/src/utils/helpers/zod-validation.ts (1)
  • buildZodSchemaValidator (11-15)
api/src/chat/schemas/types/pattern.ts (1)
  • stringRegexPatternSchema (35-51)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: API-Tests
  • GitHub Check: Frontend Tests
🔇 Additional comments (16)
api/src/utils/test/fixtures/contextvar.ts (2)

21-21: Pattern format seems consistent with implementation

The addition of the pattern: '/.+/' property to the contentVarDefaultValues object aligns with the PR objectives for regex validation of context variables. The default pattern /.+/ will match one or more of any character.


2-2: Copyright year updated appropriately

The copyright year has been updated to 2025, keeping the license information current.

api/src/chat/controllers/context-var.controller.spec.ts (1)

106-106: Test case properly includes new pattern property

The test case for context variable creation now includes the pattern property with the default value /.+/, ensuring the new functionality is properly tested.

frontend/src/types/context-var.types.ts (2)

17-17: Interface properly updated with optional pattern property

The IContextVarAttributes interface has been correctly updated to include the optional pattern property of type string, ensuring type safety when working with context variables in the frontend.


2-2: Copyright year updated

The copyright year has been updated to 2025 in the license header.

api/src/chat/dto/context-var.dto.ts (3)

30-36: Well-implemented pattern property with appropriate validation

The pattern property has been properly added to the ContextVarCreateDto class with appropriate decorators:

  • @ApiPropertyOptional for API documentation
  • @IsOptional() to mark it as optional
  • @IsString() for type validation

This implementation supports the PR objective of adding regex validation for context variables.


9-9: Import updated to include required decorator

The import statement has been properly updated to include ApiPropertyOptional which is used for the new pattern property.


2-2: Copyright year updated

The copyright year has been updated to 2025 in the license header.

api/src/chat/schemas/context-var.schema.ts (3)

2-2: Updated copyright year from 2024 to 2025

The copyright year has been updated to reflect the current year.


13-16: Added imports for validation functions

The imports for buildZodSchemaValidator and stringRegexPatternSchema have been added to support the new validation functionality for the pattern property.


46-51: Added new optional 'pattern' property with validation

The implementation adds a new optional property pattern to the ContextVar class, which allows for regex pattern validation of context variables. The default value of /.+/ will match any non-empty string.

The property:

  • Uses the Zod validation schema for regex patterns
  • Has a sensible default that matches any non-empty string
  • Is correctly marked as optional with the ? operator

This addition supports the PR objective of allowing multiple contextVars within the same block without value interference.

frontend/src/components/visual-editor/form/inputs/triggers/PatternInput.tsx (1)

29-29: Exported isRegex function for reuse

The isRegex function has been changed from a private constant to an exported function, allowing it to be used in other components. This change supports code reusability and consistency in regex pattern validation across the application.

api/src/chat/services/context-var.service.ts (1)

2-2: Updated copyright year from 2024 to 2025

The copyright year has been updated to reflect the current year.

frontend/src/components/context-vars/index.tsx (2)

12-12: Added Chip component import

The Chip component has been imported from @mui/material to support displaying patterns in the data grid.


113-121: Added pattern column to display regex in UI

A new column has been added to display the regex pattern associated with each context variable. The implementation uses a Chip component to visually represent the pattern, which enhances the user interface by making patterns easily visible and distinguishable in the data grid.

The column has appropriate configuration including flex sizing, header alignment, and disabled column menu for consistency with other columns in the grid.

frontend/src/components/context-vars/ContextVarForm.tsx (1)

174-175:

❓ Verification inconclusive

Ensure consistent format for all regex patterns

The setValueAs function is correctly ensuring that all patterns have delimiters, but there's no validation for the format of patterns coming from the backend.

Make sure all existing patterns in the database follow the format /pattern/. Run this script to verify:


🏁 Script executed:

#!/bin/bash
# Check for contextVars with invalid regex patterns

# Look for collections/models where contextVars are stored
echo "Searching for contextVars models..."

# Search for contextVar schema and pattern field
rg -A 10 "class ContextVar" --glob="*.ts"
rg "pattern.*Prop" --glob="*.ts"

# Search for any existing context variable creation/update in MongoDB queries
rg "contextVar.*pattern" --glob="*.ts"

Length of output: 5020


Regex Patterns: Validate Consistency Across Frontend and Backend

The setValueAs function in frontend/src/components/context-vars/ContextVarForm.tsx (lines 174–175) correctly adds delimiters for user input. However, our initial search of the ContextVar-related files (including schemas and seed files) did not yield a definitive confirmation that all patterns coming from the backend already adhere to the /pattern/ format.

Action Required:

  • Manually verify that all regex patterns stored in the database (e.g., in files like api/src/chat/schemas/context-var.schema.ts and api/src/chat/seeds/context-var.seed.ts) follow the /pattern/ format.
  • If any non-conforming patterns are discovered, please consider introducing backend validations or corrective transformations similar to the frontend setValueAs logic to ensure consistency.

) {
Logger.debug(
`Adding context var to subscriber: ${capture.context_var} = ${contextValue}`,
const context_var = contextVars[capture.context_var];
Copy link
Contributor

Choose a reason for hiding this comment

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

Lines 98-100.
There's obsolete commented out code. Can we get rid of it ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thank you for the feedback, your are right but.
Let's keep the update as short as possible to facilitate the review process.
I propose to create a dedicated issue for the recommended update.

Copy link
Contributor

Choose a reason for hiding this comment

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

That's a duplicate issue. I already created it previously. See the original one

@abdou6666
Copy link
Member

LGTM!
image

@@ -26,7 +26,7 @@ import {
import { OutcomeInput } from "./OutcomeInput";
import { PostbackInput } from "./PostbackInput";

const isRegex = (str: Pattern) => {
export const isRegex = (str: Pattern) => {
Copy link
Member

Choose a reason for hiding this comment

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

We can do this instead to check for regex validation:

  try {
    new RegExp(str.slice(1, -1));
    return true;
  } catch (e) {
    return false;
  }

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The isRegex function is used to detect from an input the corresponding form type to show.
If we use this function the text case will be impacted directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

💡 [REQUEST] - Add validation rules to context variables
4 participants