Skip to content

chore: Add min: 0 validation for Omnichannel agent count and order#39301

Open
dodaa08 wants to merge 6 commits intoRocketChat:developfrom
dodaa08:fix/NegativeValuesInLiveChatAgentCount
Open

chore: Add min: 0 validation for Omnichannel agent count and order#39301
dodaa08 wants to merge 6 commits intoRocketChat:developfrom
dodaa08:fix/NegativeValuesInLiveChatAgentCount

Conversation

@dodaa08
Copy link
Contributor

@dodaa08 dodaa08 commented Mar 3, 2026

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

  1. Go to Omnichannel -> Departments.
  2. Create a new department or edit an existing one.
  3. Scroll down to the Agents section and add an agent.
  4. Try to enter a negative number (e.g., -1) in the Count or Order fields.
    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

    • Enforced non-negative values for agent count and order in forms and API validation (now require >= 0), preventing invalid submissions.
  • Tests

    • Added end-to-end tests verifying negative values are rejected and zero values are accepted for agent count and order.
  • Performance

    • Memoized agent row rendering to reduce unnecessary re-renders.

@dodaa08 dodaa08 requested a review from a team as a code owner March 3, 2026 18:25
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Mar 3, 2026

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Mar 3, 2026

⚠️ No Changeset found

Latest commit: cba231d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 3, 2026

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Added 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 count/order and acceptance of zero values.

Changes

Cohort / File(s) Summary
Agent Row Component
apps/meteor/client/views/omnichannel/departments/DepartmentAgentsTable/AgentRow.tsx
Added min: 0 to registered form fields agentList[].count and agentList[].order; exported component as export default memo(AgentRow).
End-to-end tests
apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
Added three CE tests: 400 response for negative count, 400 for negative order, and success when count: 0 and order: 0.
REST typings / JSON Schemas
packages/rest-typings/src/v1/omnichannel.ts
Added minimum: 0 constraints for numeric count and order fields in POST schemas (upsert/remove and nullable agents entries).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding minimum value validation (min: 0) for agent count and order fields in the Omnichannel department module, which is reflected across all three modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 1 file

Copy link
Member

@KevLehman KevLehman left a comment

Choose a reason for hiding this comment

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

Add server validations & api tests pls

@dodaa08
Copy link
Contributor Author

dodaa08 commented Mar 3, 2026

Add server validations & api tests pls

Alright

@dodaa08 dodaa08 requested review from a team as code owners March 3, 2026 19:13
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: 1

🧹 Nitpick comments (1)
packages/rest-typings/src/v1/omnichannel.ts (1)

214-221: Consider whether validation on remove array is necessary.

Applying minimum: 0 validation to the remove array's count and order fields 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

📥 Commits

Reviewing files that changed from the base of the PR and between f58d613 and b510c76.

📒 Files selected for processing (2)
  • apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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 count and order fields 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: 0 constraints for count and order in 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: 0 validation for count and order in the POSTLivechatDepartmentSchema.agents array 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 transcriptEmail has been reformatted for readability. No semantic changes.


4376-4380: Formatting-only change, no functional impact.

The type union for POSTLivechatRoomsCloseAll has been reformatted. No semantic changes.

Comment on lines +943 to +951
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);
});
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 | 🟡 Minor

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.

Suggested change
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.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

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.

@dodaa08
Copy link
Contributor Author

dodaa08 commented Mar 3, 2026

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.

@dodaa08 dodaa08 requested a review from KevLehman March 3, 2026 19:46
@codecov
Copy link

codecov bot commented Mar 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.87%. Comparing base (b7ff7b2) to head (a5d8cb3).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             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     
Flag Coverage Δ
e2e 60.37% <ø> (+0.01%) ⬆️
e2e-api 47.80% <ø> (+0.03%) ⬆️
unit 71.58% <ø> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevLehman KevLehman added the stat: QA assured Means it has been tested and approved by a company insider label Mar 3, 2026
@KevLehman KevLehman added this to the 8.3.0 milestone Mar 3, 2026
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Mar 3, 2026
@dionisio-bot dionisio-bot bot enabled auto-merge March 3, 2026 21:27
await deleteDepartment(dep._id);
});
it('should fail if order is negative', async () => {
await updatePermission('manage-livechat-departments', ['admin']);
Copy link
Member

Choose a reason for hiding this comment

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

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']);
Copy link
Member

Choose a reason for hiding this comment

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

same with these

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()]);
Copy link
Member

Choose a reason for hiding this comment

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

and with these

.expect(400);
expect(res.body).to.have.property('success', false);
expect(res.body.error).to.include('must be >= 0');
await deleteDepartment(dep._id);
Copy link
Member

Choose a reason for hiding this comment

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

this should be on an after

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this should be on an after

I grouped these into a nested describe block with before/after hooks, are we good to go ?

auto-merge was automatically disabled March 4, 2026 04:47

Head branch was pushed to by a user without write access

@dionisio-bot dionisio-bot bot removed the stat: ready to merge PR tested and approved waiting for merge label Mar 4, 2026
@dionisio-bot dionisio-bot bot enabled auto-merge March 4, 2026 04:47
@dodaa08 dodaa08 requested a review from KevLehman March 4, 2026 04:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider type: bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants