chore: Add min: 0 validation for Omnichannel agent count and order#39301
chore: Add min: 0 validation for Omnichannel agent count and order#39301dodaa08 wants to merge 6 commits intoRocketChat:developfrom
Conversation
|
Looks like this PR is ready to merge! 🎉 |
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdded minimum (0) constraints to agent numeric fields in UI and API schemas; exported AgentRow as a memoized default; added end-to-end tests verifying rejection of negative Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
KevLehman
left a comment
There was a problem hiding this comment.
Add server validations & api tests pls
Alright |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/rest-typings/src/v1/omnichannel.ts (1)
214-221: Consider whether validation onremovearray is necessary.Applying
minimum: 0validation to theremovearray'scountandorderfields is consistent but perhaps overly strict—these values are typically echoed back from the UI and aren't functionally significant during removal operations. This isn't a bug, just a minor observation about strictness.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/rest-typings/src/v1/omnichannel.ts` around lines 214 - 221, The schema currently applies minimum: 0 to the count and order fields inside the remove array items; either remove the minimum constraint or make those properties optional on the remove item schema (i.e., drop the minimum: 0 entries for count and order or change their schema to allow absence) so echoed UI values aren't strictly validated; update the remove item definition where count and order are declared to reflect this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/meteor/tests/end-to-end/api/livechat/10-departments.ts`:
- Around line 943-951: The test "should successfully add an agent when count and
order are 0" creates resources but doesn't set the required permissions or clean
them up; update the test to call the same permission-setup helper used by the
nearby tests before making the POST (so the request has the same permission
context), and ensure the created department (and agent if applicable) are
removed after the test — either by adding cleanup calls (e.g.,
removeDepartment/deleteDepartment and removeAgent/deleteAgent) in a finally
block inside the test or by registering them for deletion in an afterEach
cleanup routine using the same helpers other tests use; reference the existing
helpers createDepartment, createAgent and the permission helper used in the
surrounding tests to implement this.
---
Nitpick comments:
In `@packages/rest-typings/src/v1/omnichannel.ts`:
- Around line 214-221: The schema currently applies minimum: 0 to the count and
order fields inside the remove array items; either remove the minimum constraint
or make those properties optional on the remove item schema (i.e., drop the
minimum: 0 entries for count and order or change their schema to allow absence)
so echoed UI values aren't strictly validated; update the remove item definition
where count and order are declared to reflect this change.
ℹ️ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/meteor/tests/end-to-end/api/livechat/10-departments.tspackages/rest-typings/src/v1/omnichannel.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.tspackages/rest-typings/src/v1/omnichannel.ts
🧠 Learnings (9)
📓 Common learnings
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39230
File: apps/meteor/app/api/server/v1/chat.ts:214-222
Timestamp: 2026-03-03T11:11:45.505Z
Learning: In apps/meteor/server/lib/moderation/reportMessage.ts, the reportMessage function validates that description is not empty or whitespace-only with `if (!description.trim())`. When migrating the chat.reportMessage endpoint to OpenAPI, adding minLength validation to the schema preserves this existing behavior.
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : All test files must be created in `apps/meteor/tests/e2e/` directory
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Group related tests in the same file
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `expect` matchers for assertions (`toEqual`, `toContain`, `toBeTruthy`, `toHaveLength`, etc.) instead of `assert` statements in Playwright tests
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.tspackages/rest-typings/src/v1/omnichannel.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
apps/meteor/tests/end-to-end/api/livechat/10-departments.tspackages/rest-typings/src/v1/omnichannel.ts
📚 Learning: 2026-03-03T11:11:45.505Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39230
File: apps/meteor/app/api/server/v1/chat.ts:214-222
Timestamp: 2026-03-03T11:11:45.505Z
Learning: In apps/meteor/server/lib/moderation/reportMessage.ts, the reportMessage function validates that description is not empty or whitespace-only with `if (!description.trim())`. When migrating the chat.reportMessage endpoint to OpenAPI, adding minLength validation to the schema preserves this existing behavior.
Applied to files:
packages/rest-typings/src/v1/omnichannel.ts
🧬 Code graph analysis (2)
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts (2)
apps/meteor/tests/data/livechat/rooms.ts (1)
createAgent(254-268)packages/core-services/src/index.ts (1)
api(61-61)
packages/rest-typings/src/v1/omnichannel.ts (1)
packages/core-typings/src/IRoom.ts (1)
IOmnichannelRoom(261-312)
🔇 Additional comments (5)
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts (1)
918-941: LGTM! Well-structured negative validation tests.The tests correctly verify that the API rejects negative values for
countandorderfields with appropriate 400 status codes and error messages.packages/rest-typings/src/v1/omnichannel.ts (4)
189-194: LGTM! Non-negative constraints correctly applied to upsert schema.The
minimum: 0constraints forcountandorderin the upsert array ensure server-side validation matches the client-side form validation added in AgentRow.tsx.
831-840: LGTM! Constraints properly added to department creation endpoint.The
minimum: 0validation forcountandorderin thePOSTLivechatDepartmentSchema.agentsarray aligns with the other schema changes and ensures consistency across all department-agent endpoints.
2857-2864: Formatting-only change, no functional impact.The type union for
transcriptEmailhas been reformatted for readability. No semantic changes.
4376-4380: Formatting-only change, no functional impact.The type union for
POSTLivechatRoomsCloseAllhas been reformatted. No semantic changes.
| it('should successfully add an agent when count and order are 0', async () => { | ||
| const [dep, agent] = await Promise.all([createDepartment(), createAgent()]); | ||
| const res = await request | ||
| .post(api(`livechat/department/${dep._id}/agents`)) | ||
| .set(credentials) | ||
| .send({ upsert: [{ agentId: agent._id, username: agent.username, count: 0, order: 0 }], remove: [] }) | ||
| .expect(200); | ||
| expect(res.body).to.have.property('success', true); | ||
| }); |
There was a problem hiding this comment.
Missing cleanup and permission setup for boundary test.
This test doesn't clean up the department after creation, which could leave stale data. Additionally, unlike the tests immediately above it (lines 918-941), this test doesn't set up permissions before running.
🧹 Proposed fix to add cleanup and maintain consistency
it('should successfully add an agent when count and order are 0', async () => {
+ await updatePermission('manage-livechat-departments', ['admin']);
+ await updatePermission('add-livechat-department-agents', ['admin', 'livechat-manager']);
const [dep, agent] = await Promise.all([createDepartment(), createAgent()]);
const res = await request
.post(api(`livechat/department/${dep._id}/agents`))
.set(credentials)
.send({ upsert: [{ agentId: agent._id, username: agent.username, count: 0, order: 0 }], remove: [] })
.expect(200);
expect(res.body).to.have.property('success', true);
+ await deleteDepartment(dep._id);
});📝 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.
| it('should successfully add an agent when count and order are 0', async () => { | |
| const [dep, agent] = await Promise.all([createDepartment(), createAgent()]); | |
| const res = await request | |
| .post(api(`livechat/department/${dep._id}/agents`)) | |
| .set(credentials) | |
| .send({ upsert: [{ agentId: agent._id, username: agent.username, count: 0, order: 0 }], remove: [] }) | |
| .expect(200); | |
| expect(res.body).to.have.property('success', true); | |
| }); | |
| it('should successfully add an agent when count and order are 0', async () => { | |
| await updatePermission('manage-livechat-departments', ['admin']); | |
| await updatePermission('add-livechat-department-agents', ['admin', 'livechat-manager']); | |
| const [dep, agent] = await Promise.all([createDepartment(), createAgent()]); | |
| const res = await request | |
| .post(api(`livechat/department/${dep._id}/agents`)) | |
| .set(credentials) | |
| .send({ upsert: [{ agentId: agent._id, username: agent.username, count: 0, order: 0 }], remove: [] }) | |
| .expect(200); | |
| expect(res.body).to.have.property('success', true); | |
| await deleteDepartment(dep._id); | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/meteor/tests/end-to-end/api/livechat/10-departments.ts` around lines 943
- 951, The test "should successfully add an agent when count and order are 0"
creates resources but doesn't set the required permissions or clean them up;
update the test to call the same permission-setup helper used by the nearby
tests before making the POST (so the request has the same permission context),
and ensure the created department (and agent if applicable) are removed after
the test — either by adding cleanup calls (e.g.,
removeDepartment/deleteDepartment and removeAgent/deleteAgent) in a finally
block inside the test or by registering them for deletion in an afterEach
cleanup routine using the same helpers other tests use; reference the existing
helpers createDepartment, createAgent and the permission helper used in the
surrounding tests to implement this.
There was a problem hiding this comment.
1 issue found across 2 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/meteor/tests/end-to-end/api/livechat/10-departments.ts">
<violation number="1" location="apps/meteor/tests/end-to-end/api/livechat/10-departments.ts:921">
P2: New tests add department/agent fixtures without cleanup, potentially leaking state across the e2e suite. The three new tests create departments and agents but do not clean them up with `deleteDepartment()`, unlike most other tests in this file.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
|
hey @KevLehman I have added validations to server for the value to be minimum 0 and some tests covering the behaviour, let me know any changes needed, thanks. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #39301 +/- ##
===========================================
+ Coverage 70.85% 70.87% +0.01%
===========================================
Files 3208 3208
Lines 113431 113431
Branches 20542 20549 +7
===========================================
+ Hits 80376 80398 +22
+ Misses 31004 30986 -18
+ Partials 2051 2047 -4
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
| await deleteDepartment(dep._id); | ||
| }); | ||
| it('should fail if order is negative', async () => { | ||
| await updatePermission('manage-livechat-departments', ['admin']); |
There was a problem hiding this comment.
move these to be in before/after hooks
| }); | ||
| it('should fail if order is negative', async () => { | ||
| await updatePermission('manage-livechat-departments', ['admin']); | ||
| await updatePermission('add-livechat-department-agents', ['admin', 'livechat-manager']); |
| it('should fail if order is negative', async () => { | ||
| await updatePermission('manage-livechat-departments', ['admin']); | ||
| await updatePermission('add-livechat-department-agents', ['admin', 'livechat-manager']); | ||
| const [dep, agent] = await Promise.all([createDepartment(), createAgent()]); |
| .expect(400); | ||
| expect(res.body).to.have.property('success', false); | ||
| expect(res.body.error).to.include('must be >= 0'); | ||
| await deleteDepartment(dep._id); |
There was a problem hiding this comment.
this should be on an after
I grouped these into a nested describe block with before/after hooks, are we good to go ?
Head branch was pushed to by a user without write access
Proposed changes (including videos or screenshots)
In the Omnichannel Department settings, the "Count" (agent weight) and "Order" fields were missing minimum value constraints. Entering negative numbers there is logically invalid and can cause the routing engine to fail or miscalculate when distributing chats.
Before
Screencast.From.2026-03-03.23-45-50.mp4
After
Screencast.From.2026-03-03.23-13-18.mp4
Updated AgentRow.tsx to include min: 0 in the register options. This ensures that the form is marked as invalid if negative numbers are entered, which in turn disables the "Save" button in the parent form.
Steps to test or reproduce
Observe that the Save button becomes disabled.
Further comments
This is a straightforward validation fix to prevent invalid data from reaching the backend and causing unpredictable routing behavior.
Summary by CodeRabbit
Bug Fixes
Tests
Performance