Skip to content

Conversation

@medtaher123
Copy link
Contributor

@medtaher123 medtaher123 commented Feb 11, 2025

Motivation

Changed the mid field in the Message schema from string to [string].

Reason for the Change:

In some channels (like Slack), certain elements must be sent as multiple separate messages. For example:

  • An attachment with a quick reply in Slack requires two separate messages, each with its own mid.

To handle this, we now store mid as an array of strings in our message object, allowing multiple message IDs to be linked to a single logical message in our database.

Summary by CodeRabbit

  • New Features

    • Enhanced support for message IDs to allow handling of multiple IDs (mid can now be a string or an array of strings) across message creation, storage, and retrieval.
  • Bug Fixes

    • Improved consistency in processing and comparing message IDs, ensuring reliable handling whether mid is a string or an array.
  • Tests

    • Updated and expanded test cases to cover scenarios where message IDs are arrays, ensuring robust validation of the new behavior.
  • Chores

    • Updated copyright years.
    • Adjusted import ordering for improved code organization.

@yassinedorbozgithub yassinedorbozgithub added the question Further information is requested label Jul 10, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

Walkthrough

The changes expand support for the mid (message ID) field across the codebase, allowing it to be either a string or an array of strings. This affects DTOs, schemas, handlers, tests, and fixtures, ensuring consistent handling of both single and multiple message IDs throughout message creation, storage, and retrieval.

Changes

File(s) Change Summary
api/src/channel/lib/Handler.ts Updated sendMessage method return type to support `mid: string
api/src/chat/dto/message.dto.ts Changed mid property in MessageCreateDto from string to `string
api/src/chat/schemas/message.schema.ts Changed mid in MessageStub to `string
api/src/extensions/channels/web/base-web-channel.ts Modified formatMessages to extract mid as first element if array, for both incoming and outgoing messages.
api/src/utils/test/fixtures/message.ts Updated fixture: second message's mid is now an array; reordered imports.
api/src/chat/controllers/message.controller.spec.ts
api/src/chat/services/message.service.spec.ts
api/src/chat/repositories/message.repository.spec.ts
Added toArray helper; updated tests to handle mid as string or array; normalized comparisons and assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Service
    participant Repository
    participant Schema

    Client->>Controller: Send/Create/Fetch message (mid: string | string[])
    Controller->>Service: Pass message DTO (mid: string | string[])
    Service->>Repository: Store/Retrieve message (mid: string | string[])
    Repository->>Schema: Save/Query message (mid: string | string[])
    Schema-->>Repository: Return message (mid: string | string[])
    Repository-->>Service: Return message (mid: string | string[])
    Service-->>Controller: Return message (mid: string | string[])
    Controller-->>Client: Return message (mid: string | string[])
Loading

Poem

🐇
A message may have one ID,
Or now, a cluster—what a spree!
Arrays or strings, we hop along,
Making sure all tests stay strong.
With every change, we leap ahead,
Multiple mids—enough said!
—Rabbit, with code and glee

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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
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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 457d49c and 6ecfbc5.

📒 Files selected for processing (8)
  • api/src/channel/lib/Handler.ts (1 hunks)
  • api/src/chat/controllers/message.controller.spec.ts (3 hunks)
  • api/src/chat/dto/message.dto.ts (3 hunks)
  • api/src/chat/repositories/message.repository.spec.ts (3 hunks)
  • api/src/chat/schemas/message.schema.ts (3 hunks)
  • api/src/chat/services/message.service.spec.ts (2 hunks)
  • api/src/extensions/channels/web/base-web-channel.ts (2 hunks)
  • api/src/utils/test/fixtures/message.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (5)
api/src/chat/controllers/message.controller.spec.ts (3)
Learnt from: yassinedorbozgithub
PR: Hexastack/Hexabot#1137
File: api/src/utils/test/utils.ts:262-262
Timestamp: 2025-06-19T07:24:22.565Z
Learning: In the Hexabot codebase's `buildTestingMocks` function, the type cast `autoInjectFrom as ToUnionArray<typeof autoInjectFrom>` is necessary due to the discriminated union with literal array types like `'providers'[]` and `'controllers'[]`. Without this cast, TypeScript compilation fails when calling `.includes()` with string literals not in the constrained type.
Learnt from: yassinedorbozgithub
PR: Hexastack/Hexabot#1137
File: api/src/utils/test/utils.ts:262-262
Timestamp: 2025-06-19T07:24:22.565Z
Learning: In TypeScript discriminated unions with literal array types like `'providers'[]` vs `'controllers'[]`, calling `.includes()` with string literals not in the constrained type causes compilation errors. Type assertions with utility types like `ToUnionArray` are necessary to unify these types for common array operations.
Learnt from: yassinedorbozgithub
PR: Hexastack/Hexabot#1137
File: api/src/utils/test/utils.ts:262-262
Timestamp: 2025-06-19T07:24:22.565Z
Learning: In TypeScript discriminated unions with different array literal types (like `'providers'[]` vs `'controllers'[]`), calling `.includes()` with values not in the literal type will cause compilation errors. Type assertions may be necessary to unify these types for common operations.
api/src/chat/dto/message.dto.ts (1)
Learnt from: medchedli
PR: Hexastack/Hexabot#1096
File: api/src/chat/repositories/block.repository.ts:0-0
Timestamp: 2025-07-03T17:41:54.853Z
Learning: In the Hexabot block schema, a block is designed so that it can never simultaneously have both an `attachedBlock` and non-empty `nextBlocks`; the two are mutually exclusive.
api/src/chat/schemas/message.schema.ts (1)
Learnt from: medchedli
PR: Hexastack/Hexabot#1096
File: api/src/chat/repositories/block.repository.ts:0-0
Timestamp: 2025-07-03T17:41:54.853Z
Learning: In the Hexabot block schema, a block is designed so that it can never simultaneously have both an `attachedBlock` and non-empty `nextBlocks`; the two are mutually exclusive.
api/src/chat/repositories/message.repository.spec.ts (1)
Learnt from: medchedli
PR: Hexastack/Hexabot#1096
File: api/src/chat/repositories/block.repository.ts:0-0
Timestamp: 2025-07-03T17:41:54.853Z
Learning: In the Hexabot block schema, a block is designed so that it can never simultaneously have both an `attachedBlock` and non-empty `nextBlocks`; the two are mutually exclusive.
api/src/chat/services/message.service.spec.ts (2)
Learnt from: yassinedorbozgithub
PR: Hexastack/Hexabot#1137
File: api/src/utils/test/utils.ts:262-262
Timestamp: 2025-06-19T07:24:22.565Z
Learning: In the Hexabot codebase's `buildTestingMocks` function, the type cast `autoInjectFrom as ToUnionArray<typeof autoInjectFrom>` is necessary due to the discriminated union with literal array types like `'providers'[]` and `'controllers'[]`. Without this cast, TypeScript compilation fails when calling `.includes()` with string literals not in the constrained type.
Learnt from: yassinedorbozgithub
PR: Hexastack/Hexabot#1137
File: api/src/utils/test/utils.ts:262-262
Timestamp: 2025-06-19T07:24:22.565Z
Learning: In TypeScript discriminated unions with literal array types like `'providers'[]` vs `'controllers'[]`, calling `.includes()` with string literals not in the constrained type causes compilation errors. Type assertions with utility types like `ToUnionArray` are necessary to unify these types for common array operations.
🧬 Code Graph Analysis (1)
api/src/chat/services/message.service.spec.ts (1)
api/src/utils/test/fixtures/message.ts (1)
  • messageFixtures (53-56)
🔇 Additional comments (12)
api/src/utils/test/fixtures/message.ts (1)

30-30: Good addition of array format for testing.

The fixture update correctly demonstrates the new capability to handle multiple message IDs, which aligns with the PR objective for supporting channels like Slack that require multiple separate messages.

api/src/chat/services/message.service.spec.ts (2)

108-110: Well-implemented helper function.

The toArray helper function correctly normalizes the union type (string | string[]) to a consistent array format for testing, ensuring proper handling of both scenarios.


120-126: Correct test logic update.

The test logic properly uses the helper function to normalize mid values for consistent comparison, supporting both single and multiple message ID scenarios.

api/src/channel/lib/Handler.ts (1)

217-217: Verify Handler.sendMessage implementations
Please confirm that every class extending Handler in api/src/channel/lib/Handler.ts has its sendMessage override updated to return { mid: string | string[] }. Manual review is required to ensure no handlers still expect a single-string return.

api/src/chat/repositories/message.repository.spec.ts (3)

63-65: Well-implemented normalization helper.

The toArray function provides a clean way to normalize mid values consistently, handling both string and array cases correctly.


67-90: Good test coverage for both mid types.

Splitting the test into separate cases for string and array mid values ensures comprehensive coverage of the new dual-type functionality. The JSON.stringify comparison approach correctly handles array equality.


91-114: Consistent test implementation.

The second test case follows the same pattern as the first, maintaining consistency in the test suite structure and approach.

api/src/extensions/channels/web/base-web-channel.ts (2)

245-245: Correct extraction of first mid element.

Using anyMessage.mid?.[0] safely extracts the first message ID from the array while handling the case where mid might be undefined or a single string. This is appropriate for the web channel format.


254-254: Proper fallback for outgoing messages.

The logic correctly extracts the first mid element and falls back to generating a new ID when mid is absent or empty. This maintains consistency with the incoming message handling above.

api/src/chat/controllers/message.controller.spec.ts (3)

144-146: Consistent normalization helper implementation.

The toArray function matches the implementation in the repository test file, providing consistency across the test suite.


169-175: Well-adapted test logic for dual-type mid support.

The test correctly uses the toArray helper and JSON.stringify comparison to handle both string and array mid values, ensuring the fixture matching works properly.


186-192: Consistent test pattern application.

The second test case follows the same pattern as the first, maintaining consistency in the test implementation approach.

Comment on lines 28 to +30
@IsOptional()
@IsString()
mid?: string;
mid?: string | string[];
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

Fix validation decorator for union type.

The @IsString() decorator only validates string types, but the mid property now accepts string | string[]. This will cause validation failures when mid is provided as an array.

Apply this diff to fix the validation:

-  @IsString()
-  mid?: string | string[];
+  @IsString({ each: true })
+  mid?: string | string[];

Or use a custom validation approach:

-  @IsString()
+  @IsString({ each: true })
+  @Transform(({ value }) => Array.isArray(value) ? value : [value])
   mid?: string | string[];

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In api/src/chat/dto/message.dto.ts around lines 28 to 30, the mid property is
typed as string or string array but only has the @IsString() decorator, which
fails validation for arrays. Replace @IsString() with a validation decorator
that supports both string and string array types, such as @IsString({ each: true
}) combined with a check for array or string, or implement a custom validator to
handle the union type correctly.

Comment on lines +99 to +100
const MessageSchema = SchemaFactory.createForClass(MessageStub);
MessageSchema.index({ mid: 1 });
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider database migration strategy.

The schema change from string to array may require migrating existing data. Verify how existing messages with string mid values will be handled.


🏁 Script executed:

#!/bin/bash
# Description: Check for existing database migration scripts or strategies
# Expected: Migration scripts should handle converting string mid to array format

fd -e js -e ts migration | xargs grep -l "mid\|message"

Length of output: 204


🏁 Script executed:

#!/bin/bash
# Inspect migration files for handling of converting string mid to array

# 1. Show occurrences of 'mid' in all migration-related code
grep -R "mid" -n api/src/migration

# 2. Show occurrences of 'message' in the specific versioned migration
grep -R "message" -n api/src/migration/migrations/1735836154221-v-2-2-0.migration.ts

# 3. Dump the first 200 lines of the migration to review its up/down logic
sed -n '1,200p' api/src/migration/migrations/1735836154221-v-2-2-0.migration.ts

Length of output: 9834


Add migration to convert existing message.mid values from string to array

We didn’t find any migration handling the mid type change—existing documents will break when mid becomes an array. Please extend your migration script to wrap any string mid in an array:

• File: api/src/migration/migrations/1735836154221-v-2-2-0.migration.ts
After your other MessageModel updates, add something like:

// Convert string mid to array
const MessageModel = mongoose.model<Message>(Message.name, messageSchema);
await MessageModel.updateMany(
  { mid: { $type: 'string' } },
  [
    { $set: { mid: { $cond: { if: { $isArray: '$mid' }, then: '$mid', else: ['$mid'] } } } }
  ]
);
logger.log('Migrated string mid to array for existing messages');
🤖 Prompt for AI Agents
In api/src/migration/migrations/1735836154221-v-2-2-0.migration.ts after your
existing MessageModel updates, add a migration step to convert any string mid
fields to arrays. Use mongoose's updateMany with a pipeline that checks if mid
is already an array; if not, wrap it in an array. This ensures existing
documents with string mids are compatible with the new schema expecting an
array. Also, add a log statement confirming the migration ran successfully.

Comment on lines +23 to +27
type: [String],
required: false,
//TODO : add default value for mid
})
mid?: string;
mid?: string | string[];
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

Fix schema type inconsistency.

There's a mismatch between the Mongoose schema definition and TypeScript type:

  • Mongoose schema: type: [String] (always expects array)
  • TypeScript type: string | string[] (union type)

This could cause runtime errors when saving string values.

Apply this diff to fix the schema definition:

   @Prop({
-    type: [String],
+    type: MongooseSchema.Types.Mixed,
     required: false,
     //TODO : add default value for mid
   })

Or use a custom schema type that handles both cases:

   @Prop({
-    type: [String],
+    type: MongooseSchema.Types.Mixed,
+    validate: {
+      validator: function(v: any) {
+        return typeof v === 'string' || (Array.isArray(v) && v.every(item => typeof item === 'string'));
+      },
+      message: 'mid must be a string or array of strings'
+    },
     required: false,
     //TODO : add default value for mid
   })
🤖 Prompt for AI Agents
In api/src/chat/schemas/message.schema.ts around lines 23 to 27, fix the
inconsistency between the Mongoose schema and TypeScript type for the mid field.
Update the Mongoose schema type to accept both a single string and an array of
strings, or adjust the TypeScript type to match the schema by making mid always
an array of strings. Ensure the schema and TypeScript types align to prevent
runtime errors when saving string values.

@medchedli medchedli removed the question Further information is requested label Sep 15, 2025
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