Skip to content

fix(bot): defer autoplay/buttons, non-blocking play, dedup versions - #513

Merged
LucasSantana-Dev merged 2 commits into
mainfrom
fix/perf-autoplay-buttons
Apr 10, 2026
Merged

LucasSantana-Dev merged 2 commits into
mainfrom
fix/perf-autoplay-buttons

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • /autoplay 5-10s lag: added deferReply() before DB calls — Discord was timing out waiting for the initial acknowledgement
  • Buttons "This interaction failed": deferUpdate() is now the very first operation in handleMusicButtonInteraction (before voice/queue checks). Error messages use followUp({ ephemeral: true }) since the interaction is already deferred
  • /play slow reply: applyStoredAutoplayPreference (DB) and blendAutoplayTracks (Spotify API) now run fire-and-forget after interactionReply — user gets the "Now Playing" embed immediately
  • Autoplay default ON: guilds without a stored preference now default to autoplay enabled on new queues (?? true)
  • Repeated songs in autoplay: normalizeTrackKey now uses cleanTitle/cleanAuthor before hashing, so "(Live)", "(Acoustic)", "(Cover)", "(Remix)", "(Instrumental)", etc. are stripped before comparison — versions of the same song are caught as duplicates. Also added 17 new version-variant noise patterns to searchQueryCleaner.ts

Test plan

  • 1674 tests green
  • /autoplay responds immediately (no "thinking..." lag)
  • All music buttons (pause/resume/skip/shuffle/loop/queue/leaderboard) work without "This interaction failed"
  • /play sends "Now Playing" embed immediately; autoplay queue fills in background
  • New guilds get autoplay ON by default
  • Autoplay queue doesn't add "Song (Live)" when "Song" is already in history

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Better music-title cleaning to strip version/format modifiers (live, acoustic, cover, remix, instrumental, karaoke, explicit, clean, single, album, deluxe, bonus).
  • Bug Fixes

    • Fixed leaderboard truncation.
    • Improved button interaction handling for more reliable responses.
    • Hardened autoplay error handling for edge-case interaction failures.
  • Improvements

    • Post-play tasks now run in background for snappier play responses.
    • Added timestamps and friendlier error messages in music commands.
  • Documentation

    • Added a staged rollout plan for command response polish.

@vercel

vercel Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 10, 2026 1:58am

Request Review

@github-actions github-actions Bot added the bot label Apr 10, 2026
@coderabbitai

coderabbitai Bot commented Apr 10, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds a rollout plan document and implements music command interaction/flow changes: guarded interaction deferral in autoplay, earlier button deferral with followUp/editReply error handling, post-play autoplay ops moved to background tasks, and expanded track-title cleaning and normalization; tests updated for async/background behavior.

Changes

Cohort / File(s) Summary
Plan Documentation
.agents/plans/lucky-v2.6.66-command-polish.md
New staged rollout plan describing phased embed helper rollout, leaderboard pagination, track embed standardization, engagement polish, cross-cutting quality fixes, and release steps.
Autoplay Command
packages/bot/src/functions/music/commands/autoplay.ts, packages/bot/src/functions/music/commands/autoplay.spec.ts
Added guarded interaction.deferReply() with silent-return on Discord error code 10062; updated tests to cover deferReply failure paths and adjusted error-embed mock formatting.
Button Interaction Handling
packages/bot/src/handlers/musicButtonHandler.ts, packages/bot/src/handlers/musicButtonHandler.spec.ts
Now calls interaction.deferUpdate() early for button presses; error paths use followUp(...) or editReply(...) depending on deferred/replied state; tests updated to expect deferUpdate() + ephemeral followUp.
Play Command & Tests
packages/bot/src/functions/music/commands/play/index.ts, packages/bot/src/functions/music/commands/play/index.spec.ts
Moved post-play autoplay operations (applyStoredAutoplayPreference, blendAutoplayTracks) into an unawaited background task with logged errors; treat missing autoplay setting as enabled by default; tests add flushPromises() and expand mocks for post-play/background behavior.
Track Cleaning & Normalization
packages/bot/src/utils/music/searchQueryCleaner.ts, packages/bot/src/utils/music/searchQueryCleaner.spec.ts, packages/bot/src/utils/music/queueManipulation.ts
Expanded noise-removal patterns to strip parenthesized/bracketed tokens (live, acoustic, cover, remix, instrumental, karaoke, explicit, clean, single, album, deluxe, bonus track); normalizeTrackKey now applies cleanTitle/cleanAuthor before normalization; tests added for new patterns.

Sequence Diagram(s)

sequenceDiagram
    participant User as User Interaction
    participant Cmd as Play/Autoplay Command
    participant Queue as Player Queue
    participant Settings as Guild Settings
    participant Logger as Logger

    User->>Cmd: triggers /play or /autoplay
    Cmd->>User: interaction.deferReply() (guarded)
    Cmd->>Queue: enqueue track / build response embed
    Cmd->>User: interactionReply(...) with embed
    Cmd->>Cmd: start bg task (applyStoredAutoplayPreference, blendAutoplayTracks) asynchronously
    Cmd->>Settings: read stored autoplay (in bg)
    Settings-->>Cmd: stored preference
    Cmd->>Queue: update repeatMode / blend tracks (in bg)
    Cmd->>Logger: if bg error -> "Post-play background ops failed"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main changes: deferring autoplay/button interactions, making play non-blocking, and improving deduplication by stripping version tags.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/perf-autoplay-buttons

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.

@github-actions github-actions Bot removed the size/xl label Apr 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/functions/music/commands/play/index.ts`:
- Around line 308-323: play/index.ts currently treats a missing guild preference
as enabled (settings?.autoPlayEnabled ?? true) while
resolveCurrentAutoplayState() uses false; make the defaults consistent by either
importing/using the canonical default from resolveCurrentAutoplayState() or
switching the fallback in play/index.ts to the same boolean (e.g.,
settings?.autoPlayEnabled ?? false), and keep the debugLog and the
QueueRepeatMode logic (queue.setRepeatMode(repeatMode) /
QueueRepeatMode.AUTOPLAY) aligned with that same default.
- Around line 232-259: The background task started in bgOps applies stored
autoplay (applyStoredAutoplayPreference) then calls blendAutoplayTracks, but
blendAutoplayTracks returns early when autoplayTracks is empty and never calls
replenishQueue, so fresh queues never get initial autoplay fill; fix by ensuring
that when applyStoredAutoplayPreference sets queue.repeatMode to
QueueRepeatMode.AUTOPLAY (or when queue has no autoplay tracks), you directly
invoke replenishQueue(queue) (or otherwise set the autoplay state synchronously
before returning from the command) instead of relying solely on
blendAutoplayTracks to trigger replenishment; update the logic around
applyStoredAutoplayPreference, blendAutoplayTracks, and replenishQueue so
initial /play on a new queue triggers replenishQueue immediately.

In `@packages/bot/src/handlers/musicButtonHandler.ts`:
- Around line 76-87: The current error-path in musicButtonHandler.ts wrongly
calls interaction.editReply() when interaction.deferred is true, which edits the
shared component message; change the logic so that after deferUpdate() (when
interaction.deferred is true) you call interaction.followUp({ ephemeral: true,
... }) to send a private error message, and for the not-deferred path use
interaction.reply(...) (or followUp only for secondary messages) instead of
editReply(); update the branches referencing interaction.deferred, editReply(),
followUp(), and reply() so deferred interactions use followUp(ephemeral: true)
and non-deferred interactions use reply/followUp appropriately to avoid
overwriting the shared queue/leaderboard message.

In `@packages/bot/src/utils/music/queueManipulation.ts`:
- Around line 745-748: The feedback key generation is inconsistent:
normalizeTrackKey(title, author) uses cleanTitle(), cleanAuthor(), and
normalizeText() but recommendationFeedbackService.buildTrackKey() does not,
causing mismatched keys; fix by making buildTrackKey() use the same
normalization pipeline (call cleanTitle(), cleanAuthor(), then normalizeText()
for both parts) or refactor into a single shared function (e.g., export a
normalizeTrackKey helper and use it in both normalizeTrackKey and
recommendationFeedbackService.buildTrackKey) so stored feedback keys and
autoplay checks produce identical keys; ensure the unique functions
normalizeTrackKey, buildTrackKey, cleanTitle, cleanAuthor, normalizeText, and
recommendationFeedbackService are updated to use the shared normalizer (or run a
backfill to rewrite existing keys if you choose that option).

In `@packages/bot/src/utils/music/searchQueryCleaner.ts`:
- Around line 57-58: Named remix variants are still bypassing the normalizer
because the current regexes in searchQueryCleaner.ts only match bare "(Remix)" /
"[Remix]"; update those two entries (the regexes currently matching
/\(remix(?:\s{0,3}(?:version|edit))?\)/gi and
/\[remix(?:\s{0,3}(?:version|edit))?\]/gi) to broaden the pattern to also match
variants like "(Kygo Remix)", "(2024 Remix)", "(Ft. Artist Remix)", etc., by
allowing an optional non-greedy leading token before "remix" inside the
parentheses/brackets (still case-insensitive and preserving the optional
"version|edit" suffix).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8921e0a7-55b6-4704-9011-20734499d506

📥 Commits

Reviewing files that changed from the base of the PR and between 979e9b3 and e8b96df.

📒 Files selected for processing (8)
  • .agents/plans/lucky-v2.6.66-command-polish.md
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/searchQueryCleaner.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). (2)
  • GitHub Check: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/musicButtonHandler.spec.ts
  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/handlers/musicButtonHandler.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
  • packages/bot/src/utils/music/searchQueryCleaner.ts
packages/bot/src/functions/**/commands/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Discord bot commands must be structured in packages/bot/src/functions/<category>/commands/<name>.ts with handlers in <category>/handlers/

Files:

  • packages/bot/src/functions/music/commands/autoplay.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must include data (slash builder), execute, and category properties exported from packages/bot/src/models/Command.ts
Use @discordjs/builders for building the data (SlashCommandBuilder) in command definitions
Command execute function must receive { interaction, client } parameters from CommandExecuteParams type
Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling
Use existing validators from packages/bot/src/utils/command/ for voice channel, queue, and guild validations in commands

Files:

  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
packages/bot/src/functions/{general,music,download}/commands/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

packages/bot/src/functions/{general,music,download}/commands/**/*.ts: Apply .cursor/rules/lucky-discord-bot.mdc rules for Discord bot commands and player implementation
Use .cursor/skills/discord-commands/SKILL.md for implementing slash commands

Files:

  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
packages/bot/src/functions/music/commands/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use .cursor/skills/music-queue-player/SKILL.md for play, queue, skip, volume commands and player lifecycle management

Files:

  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
packages/bot/src/functions/music/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use existing voice/queue/guild validators before manipulating player or queue state

Files:

  • packages/bot/src/functions/music/commands/autoplay.ts
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/functions/music/commands/play/index.spec.ts
**/index.ts

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Use index.ts only to re-export a small, intentional surface per module

Files:

  • packages/bot/src/functions/music/commands/play/index.ts

Comment on lines +232 to +259
// Start background ops (apply autoplay pref then blend) without awaiting.
// This lets the response reach the user immediately.
// The Promise is not awaited, allowing the command handler to return while
// these operations continue processing in the background.
const bgOps = (async () => {
try {
if (!hadQueueBeforePlay && queue) {
await applyStoredAutoplayPreference(
queue,
interaction.guildId!,
)
}
if (
!isPlaylist &&
queue &&
queue.repeatMode === QueueRepeatMode.AUTOPLAY
) {
await blendAutoplayTracks(queue, track)
}
} catch (bgError) {
errorLog({
message: 'Post-play background ops failed',
error: bgError,
data: { guildId: interaction.guildId },
})
}
})()
void bgOps

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- /play background autoplay work ---'
sed -n '227,260p' packages/bot/src/functions/music/commands/play/index.ts

echo
echo '--- blendAutoplayTracks early return / refill behavior ---'
fd 'queueManipulation.ts' packages/bot/src/utils/music -x sed -n '931,965p' {}

echo
echo '--- track-end autoplay gate ---'
fd 'trackHandlers.ts' packages/bot/src/handlers/player -x sed -n '113,160p' {}

Repository: LucasSantana-Dev/Lucky

Length of output: 4040


Fresh queues miss the initial autoplay fill due to early return in blendAutoplayTracks().

The background async block (lines 238–249) defers autoplay setup until after the reply. When /play runs on a fresh queue in a new guild:

  1. applyStoredAutoplayPreference() applies the stored preference and sets queue.repeatMode to AUTOPLAY (if enabled)
  2. blendAutoplayTracks() is then called
  3. However, blendAutoplayTracks() checks for existing autoplay tracks and returns early (if (autoplayTracks.length === 0) return) before calling replenishQueue(queue)
  4. Since a fresh queue has no autoplay tracks yet, replenishment never happens and the queue remains empty

This blocks autoplay from working on the initial /play in any guild. The queue should either call replenishQueue() directly when no autoplay tracks exist, or set the repeat mode before returning from the async block to allow the track-end handler to trigger replenishment.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/music/commands/play/index.ts` around lines 232 -
259, The background task started in bgOps applies stored autoplay
(applyStoredAutoplayPreference) then calls blendAutoplayTracks, but
blendAutoplayTracks returns early when autoplayTracks is empty and never calls
replenishQueue, so fresh queues never get initial autoplay fill; fix by ensuring
that when applyStoredAutoplayPreference sets queue.repeatMode to
QueueRepeatMode.AUTOPLAY (or when queue has no autoplay tracks), you directly
invoke replenishQueue(queue) (or otherwise set the autoplay state synchronously
before returning from the command) instead of relying solely on
blendAutoplayTracks to trigger replenishment; update the logic around
applyStoredAutoplayPreference, blendAutoplayTracks, and replenishQueue so
initial /play on a new queue triggers replenishQueue immediately.

Comment on lines +308 to +323
const repeatMode =
(settings?.autoPlayEnabled ?? true)
? QueueRepeatMode.AUTOPLAY
: QueueRepeatMode.OFF

if (queue.repeatMode !== repeatMode) {
queue.setRepeatMode(repeatMode)
}

debugLog({
message: 'Applied stored autoplay preference to queue',
data: { guildId, autoPlayEnabled: settings.autoPlayEnabled },
})
if (queue.repeatMode !== repeatMode) {
queue.setRepeatMode(repeatMode)
}

debugLog({
message: 'Applied stored autoplay preference to queue',
data: {
guildId,
autoPlayEnabled: settings?.autoPlayEnabled ?? true,
},
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

/play and /autoplay now disagree on the unset default.

Lines 308-310 treat a missing guild preference as enabled, but resolveCurrentAutoplayState() in packages/bot/src/functions/music/commands/autoplay.ts:178-187 still falls back to false. In a new guild, /play starts with autoplay on, while the first /autoplay toggle will persist enabled instead of disabling it.

Align both call sites to the same default before shipping.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/music/commands/play/index.ts` around lines 308 -
323, play/index.ts currently treats a missing guild preference as enabled
(settings?.autoPlayEnabled ?? true) while resolveCurrentAutoplayState() uses
false; make the defaults consistent by either importing/using the canonical
default from resolveCurrentAutoplayState() or switching the fallback in
play/index.ts to the same boolean (e.g., settings?.autoPlayEnabled ?? false),
and keep the debugLog and the QueueRepeatMode logic
(queue.setRepeatMode(repeatMode) / QueueRepeatMode.AUTOPLAY) aligned with that
same default.

Comment on lines +76 to 87
if (interaction.deferred) {
await interaction
.reply({
.editReply({
embeds: [createErrorEmbed('Error', 'Something went wrong')],
ephemeral: true,
})
.catch(() => {})
} else if (interaction.deferred) {
} else if (!interaction.replied) {
await interaction
.editReply({
.followUp({
embeds: [createErrorEmbed('Error', 'Something went wrong')],
ephemeral: true,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In the official discord.js docs, after ButtonInteraction.deferUpdate(), does editReply edit the original component message while followUp sends a separate message? Please quote the relevant docs for deferUpdate, editReply, and followUp.

💡 Result:

Yes—per the discord.js docs:

  • deferUpdate(): “Defers an update to the message to which the component was attached.” [1]
  • editReply(): “Edits a reply to this interaction.” [1]
  • followUp(): “Send a follow-up message to this interaction.” [1]

So after ButtonInteraction.deferUpdate(), your “initial response” is an update to the component’s message, and editReply() edits that initial response; followUp() sends an additional (separate) message. [1]

Sources:
[1] discord.js docs — ButtonInteraction class page (methods deferUpdate, editReply, followUp). (discord.js.org)

Citations:


Don't overwrite the shared button message on deferred failures.

After Line 28 calls deferUpdate(), interaction.deferred is true on the normal error path. Lines 77–80 then call editReply(), which per the discord.js docs edits the original component message for all users, replacing the shared queue/leaderboard. This contradicts the PR goal of sending ephemeral follow-ups after deferUpdate().

After deferUpdate(), use followUp() with ephemeral: true for private errors. For un-deferred interactions, use reply() as the first response.

Suggested fix
-        if (interaction.deferred) {
+        if (interaction.deferred || interaction.replied) {
             await interaction
-                .editReply({
+                .followUp({
                     embeds: [createErrorEmbed('Error', 'Something went wrong')],
+                    ephemeral: true,
                 })
                 .catch(() => {})
-        } else if (!interaction.replied) {
+        } else {
             await interaction
-                .followUp({
+                .reply({
                     embeds: [createErrorEmbed('Error', 'Something went wrong')],
                     ephemeral: true,
                 })
                 .catch(() => {})
         }

Per discord.js docs: deferUpdate() defers an update to the component message; editReply() edits that response; followUp() sends a separate message. (discord.js ButtonInteraction)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/musicButtonHandler.ts` around lines 76 - 87, The
current error-path in musicButtonHandler.ts wrongly calls
interaction.editReply() when interaction.deferred is true, which edits the
shared component message; change the logic so that after deferUpdate() (when
interaction.deferred is true) you call interaction.followUp({ ephemeral: true,
... }) to send a private error message, and for the not-deferred path use
interaction.reply(...) (or followUp only for secondary messages) instead of
editReply(); update the branches referencing interaction.deferred, editReply(),
followUp(), and reply() so deferred interactions use followUp(ephemeral: true)
and non-deferred interactions use reply/followUp appropriately to avoid
overwriting the shared queue/leaderboard message.

Comment on lines 745 to +748
function normalizeTrackKey(title?: string, author?: string): string {
return `${normalizeText(title)}::${normalizeText(author)}`
const cleanedTitle = title ? cleanTitle(title) : ''
const cleanedAuthor = author ? cleanAuthor(author) : ''
return `${normalizeText(cleanedTitle)}::${normalizeText(cleanedAuthor)}`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- feedback key lookup call sites ---'
rg -n -C2 'getLikedTrackKeys|getDislikedTrackKeys|trackKey|normalizeTrackKey' .

echo
echo '--- feedback service implementations ---'
fd -i 'feedbackService' . -x sed -n '1,260p' {}

Repository: LucasSantana-Dev/Lucky

Length of output: 27026


🏁 Script executed:

rg -n 'function cleanTitle|function cleanAuthor|function normalizeText|const cleanTitle|const cleanAuthor|const normalizeText' packages/bot/src/utils/music/queueManipulation.ts -A 5

Repository: LucasSantana-Dev/Lucky

Length of output: 243


🏁 Script executed:

rg -n 'cleanTitle|cleanAuthor' packages/bot/src/utils/music/queueManipulation.ts -B 2 -A 5

Repository: LucasSantana-Dev/Lucky

Length of output: 834


🏁 Script executed:

cat packages/bot/src/utils/music/searchQueryCleaner.ts

Repository: LucasSantana-Dev/Lucky

Length of output: 6027


Fix the feedback-key contract mismatch before deploying.

The feedback service uses buildTrackKey() which applies only lowercase + regex stripping, while the autoplay queue manipulation now uses normalizeTrackKey() which first strips noise patterns via cleanTitle() and cleanAuthor() before the same regex stripping. These produce different keys for identical tracks.

Example: "Song (Official Video)" by "Artist - Topic"

  • Stored key (feedbackService): songofficial::artisttopic
  • Checked key (autoplay): song::artist

Existing feedback entries will not match, and disliked tracks can re-enter autoplay immediately after deploy.

Action required:

  1. Make recommendationFeedbackService.buildTrackKey() use the same cleanTitle(), cleanAuthor(), and normalizeText() helpers as normalizeTrackKey(), or
  2. Create a shared normalization function and use it in both paths, or
  3. Implement a backfill that rewrites all stored feedback keys using the new normalizer before deployment.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/music/queueManipulation.ts` around lines 745 - 748,
The feedback key generation is inconsistent: normalizeTrackKey(title, author)
uses cleanTitle(), cleanAuthor(), and normalizeText() but
recommendationFeedbackService.buildTrackKey() does not, causing mismatched keys;
fix by making buildTrackKey() use the same normalization pipeline (call
cleanTitle(), cleanAuthor(), then normalizeText() for both parts) or refactor
into a single shared function (e.g., export a normalizeTrackKey helper and use
it in both normalizeTrackKey and recommendationFeedbackService.buildTrackKey) so
stored feedback keys and autoplay checks produce identical keys; ensure the
unique functions normalizeTrackKey, buildTrackKey, cleanTitle, cleanAuthor,
normalizeText, and recommendationFeedbackService are updated to use the shared
normalizer (or run a backfill to rewrite existing keys if you choose that
option).

Comment on lines +57 to +58
/\(remix(?:\s{0,3}(?:version|edit))?\)/gi,
/\[remix(?:\s{0,3}(?:version|edit))?\]/gi,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Named remix variants still bypass this normalizer.

Lines 57-58 only match bare (Remix) / (Remix Edit) forms. Titles like Song (Kygo Remix) or Song (2024 Remix) will still hash differently, so the duplicate suppression misses many real-world remix variants.

♻️ Possible pattern broadening
-    /\(remix(?:\s{0,3}(?:version|edit))?\)/gi,
-    /\[remix(?:\s{0,3}(?:version|edit))?\]/gi,
+    /\((?:[^)]+?\s)?remix(?:\s{0,3}(?:version|edit))?\)/gi,
+    /\[(?:[^\]]+?\s)?remix(?:\s{0,3}(?:version|edit))?\]/gi,
📝 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
/\(remix(?:\s{0,3}(?:version|edit))?\)/gi,
/\[remix(?:\s{0,3}(?:version|edit))?\]/gi,
/\((?:[^)]+?\s)?remix(?:\s{0,3}(?:version|edit))?\)/gi,
/\[(?:[^\]]+?\s)?remix(?:\s{0,3}(?:version|edit))?\]/gi,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/music/searchQueryCleaner.ts` around lines 57 - 58,
Named remix variants are still bypassing the normalizer because the current
regexes in searchQueryCleaner.ts only match bare "(Remix)" / "[Remix]"; update
those two entries (the regexes currently matching
/\(remix(?:\s{0,3}(?:version|edit))?\)/gi and
/\[remix(?:\s{0,3}(?:version|edit))?\]/gi) to broaden the pattern to also match
variants like "(Kygo Remix)", "(2024 Remix)", "(Ft. Artist Remix)", etc., by
allowing an optional non-greedy leading token before "remix" inside the
parentheses/brackets (still case-insensitive and preserving the optional
"version|edit" suffix).

@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 3d1f7dd into main Apr 10, 2026
11 of 12 checks passed
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
…513)

* fix(bot): defer autoplay/buttons, non-blocking play, dedup versions

* test(bot): cover autoplay defer, version noise patterns, play bg ops
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…513)

* fix(bot): defer autoplay/buttons, non-blocking play, dedup versions

* test(bot): cover autoplay defer, version noise patterns, play bg ops
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/perf-autoplay-buttons branch May 23, 2026 02:21

This branch was successfully deployed

1 active deployment
Preview — 68e11cbc Deployed Apr 10, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant