Skip to content

chore(custom-sounds): sanitize any usage in AddCustomSound and EditSound#39044

Open
srijnabhargav wants to merge 3 commits intoRocketChat:developfrom
srijnabhargav:fix/sanitize-custom-sounds-type-assertions
Open

chore(custom-sounds): sanitize any usage in AddCustomSound and EditSound#39044
srijnabhargav wants to merge 3 commits intoRocketChat:developfrom
srijnabhargav:fix/sanitize-custom-sounds-type-assertions

Conversation

@srijnabhargav
Copy link
Copy Markdown

@srijnabhargav srijnabhargav commented Feb 25, 2026

Fixes #39043

What changed

  • Replaced any in custom-sound save callbacks with strict types
  • Removed // FIXME markers
  • Updated shared custom-sound file typing in lib.ts to support both existing data and uploaded files
  • Added safe guards for file-specific checks

Why

This improves type safety in admin custom-sound create/edit flows without changing behavior.

Impact

  • No runtime changes
  • Compile-time safety improved

Summary by CodeRabbit

  • Bug Fixes

    • Validation now tolerates missing file-type metadata and avoids runtime errors.
    • Save/upload flow short-circuits when no file is selected; uploads occur only for actual file uploads.
  • Refactor

    • Tightened handling of sound inputs (files vs. existing sound references), including safer extraction of file extensions.
    • No public component APIs were changed.

COMM-144

@srijnabhargav srijnabhargav requested a review from a team as a code owner February 25, 2026 10:39
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot bot commented Feb 25, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is targeting the wrong base branch. It should target 8.4.0, but it targets 8.1.0

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Feb 25, 2026

⚠️ No Changeset found

Latest commit: 114a5fe

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

@srijnabhargav srijnabhargav changed the title refactor : remove any usage and enforce strict typing in AddCustomSound and EditSound fix : remove any usage and enforce strict typing in AddCustomSound and EditSound Feb 25, 2026
@srijnabhargav srijnabhargav changed the title fix : remove any usage and enforce strict typing in AddCustomSound and EditSound chore(custom-sounds): sanitize any usage in AddCustomSound and EditSound Feb 25, 2026
Copy link
Copy Markdown
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 3 files

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 25, 2026

Walkthrough

This PR tightens types in the custom-sounds admin flows: AddCustomSound now treats the sound state as a File and short-circuits when none is selected; EditSound accepts File or existing sound metadata and only uploads when given a File; ICustomSoundFile.type is now optional and validations are guarded accordingly.

Changes

Cohort / File(s) Summary
Add Sound UI
apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx
Narrowed sound state to File, updated saveAction signature to accept File, short-circuited save when no file selected, and replaced any callbacks with File types.
Edit Sound UI
apps/meteor/client/views/admin/customSounds/EditSound.tsx
Updated saveAction to accept `File
Type defs & validation
apps/meteor/client/views/admin/customSounds/lib.ts
Made ICustomSoundFile.type optional (type?: string) and guarded type-based validation using 'type' in soundFile and soundFile.type ?? '' to avoid runtime errors when type is missing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: replacing any type usage with strict types in AddCustomSound and EditSound components.
Linked Issues check ✅ Passed All objectives from issue #39043 are met: any types replaced with strict types, lib.ts kept compatible with both files and existing data, FIXME comments removed, runtime-safe checks added.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue: type safety improvements in custom-sounds components and lib.ts with no unrelated modifications.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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
Copy Markdown
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/meteor/client/views/admin/customSounds/EditSound.tsx (2)

41-41: ⚠️ Potential issue | 🟡 Minor

'' is not assignable to the declared sound state type.

setSound(previousSound || '') compiles with an error because '' is not assignable to { _id: string; name: string; extension?: string } | File. Since previousSound is data || {} (always an object), the fallback is unreachable in practice, but the type error remains and contradicts the PR's strict-typing goal.

🐛 Proposed fix
-		setSound(previousSound || '');
+		setSound(previousSound);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/client/views/admin/customSounds/EditSound.tsx` at line 41, The
call setSound(previousSound || '') fails TypeScript because '' isn't compatible
with the sound state type; replace the string fallback with an object matching
the state type (or a type assertion) so the fallback is correctly typed. Locate
the sound state and the setSound call in EditSound.tsx (the variable names are
sound, setSound and previousSound/data) and change the fallback to either
previousSound ?? ({} as { _id: string; name: string; extension?: string }) or
provide a properly typed empty object constant, ensuring the value passed to
setSound matches the declared state type.

97-100: ⚠️ Potential issue | 🟠 Major

saveAction is not awaited — onChange fires before the save/upload completes.

saveAction(sound) returns a Promise; dropping the await means onChange() is called immediately regardless of whether the insert, validation, or upload succeeds or fails. Any state refresh driven by onChange will see stale data.

🐛 Proposed fix
-	const handleSave = useCallback(async () => {
-		saveAction(sound);
-		onChange();
-	}, [saveAction, sound, onChange]);
+	const handleSave = useCallback(async () => {
+		await saveAction(sound);
+		onChange();
+	}, [saveAction, sound, onChange]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/client/views/admin/customSounds/EditSound.tsx` around lines 97 -
100, handleSave currently calls saveAction(sound) without awaiting, so
onChange() runs before the save/upload finishes; change handleSave to await the
Promise returned by saveAction(sound) and call onChange only after the await
completes — i.e., wrap await saveAction(sound) in a try/catch to surface or log
errors (do not swallow), then call onChange() after the await (or rethrow the
error if appropriate); update the useCallback accordingly (keep dependencies
saveAction, sound, onChange).
🤖 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/client/views/admin/customSounds/lib.ts`:
- Line 23: The current guard uses "soundFile.type && ..." which skips MIME
validation when soundFile.type is the empty string; change the guard to detect
absence of the property instead so empty-string types still run the regex check.
Replace the truthiness check with a property-existence check (e.g., use "'type'
in soundFile" or Object.prototype.hasOwnProperty.call(soundFile, 'type')) so the
FileType validation block (the if containing the
/audio\/mp3|audio\/mpeg|audio\/x-mpeg/ regex) runs for empty-string types but
still skips for non-File shapes that genuinely lack a type property.

---

Outside diff comments:
In `@apps/meteor/client/views/admin/customSounds/EditSound.tsx`:
- Line 41: The call setSound(previousSound || '') fails TypeScript because ''
isn't compatible with the sound state type; replace the string fallback with an
object matching the state type (or a type assertion) so the fallback is
correctly typed. Locate the sound state and the setSound call in EditSound.tsx
(the variable names are sound, setSound and previousSound/data) and change the
fallback to either previousSound ?? ({} as { _id: string; name: string;
extension?: string }) or provide a properly typed empty object constant,
ensuring the value passed to setSound matches the declared state type.
- Around line 97-100: handleSave currently calls saveAction(sound) without
awaiting, so onChange() runs before the save/upload finishes; change handleSave
to await the Promise returned by saveAction(sound) and call onChange only after
the await completes — i.e., wrap await saveAction(sound) in a try/catch to
surface or log errors (do not swallow), then call onChange() after the await (or
rethrow the error if appropriate); update the useCallback accordingly (keep
dependencies saveAction, sound, onChange).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 813d57a and 737a9c3.

📒 Files selected for processing (3)
  • apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx
  • apps/meteor/client/views/admin/customSounds/EditSound.tsx
  • apps/meteor/client/views/admin/customSounds/lib.ts
📜 Review details
🧰 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/client/views/admin/customSounds/EditSound.tsx
  • apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx
  • apps/meteor/client/views/admin/customSounds/lib.ts
🧠 Learnings (2)
📚 Learning: 2026-01-17T01:51:47.764Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38219
File: packages/core-typings/src/cloud/Announcement.ts:5-6
Timestamp: 2026-01-17T01:51:47.764Z
Learning: In packages/core-typings/src/cloud/Announcement.ts, the AnnouncementSchema.createdBy field intentionally overrides IBannerSchema.createdBy (object with _id and optional username) with a string enum ['cloud', 'system'] to match existing runtime behavior. This is documented as technical debt with a FIXME comment at apps/meteor/app/cloud/server/functions/syncWorkspace/handleCommsSync.ts:53 and should not be flagged as an error until the runtime behavior is corrected.

Applied to files:

  • apps/meteor/client/views/admin/customSounds/lib.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/views/admin/customSounds/lib.ts
🧬 Code graph analysis (1)
apps/meteor/client/views/admin/customSounds/EditSound.tsx (1)
apps/meteor/client/views/admin/customSounds/lib.ts (1)
  • createSoundData (32-61)
🔇 Additional comments (1)
apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx (1)

22-22: LGTM — type narrowing and guard are correct.

State narrowed to File | undefined, saveAction signature tightened to File, and the early-return guard cleanly prevents calling saveAction without a file. The await saveAction(name, sound) on Line 78 correctly ensures errors and navigation are sequenced.

Also applies to: 34-34, 75-78

@ggazzo ggazzo added this to the 8.3.0 milestone Feb 25, 2026
@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Feb 25, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Feb 26, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.63%. Comparing base (c7966fa) to head (a472d6f).
⚠️ Report is 240 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #39044      +/-   ##
===========================================
- Coverage    70.66%   70.63%   -0.04%     
===========================================
  Files         3136     3177      +41     
  Lines       108599   112516    +3917     
  Branches     19538    20495     +957     
===========================================
+ Hits         76742    79473    +2731     
- Misses       29856    31015    +1159     
- Partials      2001     2028      +27     
Flag Coverage Δ
unit 71.23% <ø> (-0.49%) ⬇️

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 valid A valid contribution where maintainers will review based on priority label Feb 26, 2026
@scuciatto scuciatto modified the milestones: 8.3.0, 8.4.0 Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community stat: QA assured Means it has been tested and approved by a company insider type: chore valid A valid contribution where maintainers will review based on priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Type-safety: remove any usage in custom sounds admin flows

5 participants