diff --git a/index.mjs b/index.mjs index 81d8134..312f23e 100644 --- a/index.mjs +++ b/index.mjs @@ -66,8 +66,14 @@ export class Remix { }; // ── Fluxer Client ──────────────────────────────────────────────────────── + // Fluxer does NOT support intents — the value is always sent as 0 in the + // gateway IDENTIFY payload regardless of what you set here. Setting a + // non-zero value only produces a warning unless suppressIntentWarning + // is true. Always use intents: 0 for Fluxer bots. const client = new Client({ - intents: config["fluxer.js"]?.intents ?? 0, + intents: 0, + suppressIntentWarning: true, + waitForGuilds: true, ...config["fluxer.js"], presence: (() => { if (presenceContents.length === 0) return undefined; @@ -105,6 +111,14 @@ export class Remix { client.setMaxListeners(50); this.client = client; + // ── VoiceManager initialization (MUST be before login) ───────────────── + try { + getVoiceManager(client); + logger.player("[Startup] VoiceManager initialized before login."); + } catch (e) { + logger.warn("[Startup] VoiceManager pre-login init failed:", e.message); + } + // ── Message & Settings handlers ────────────────────────────────────────── const messages = new MessageHandler(this.client); this.messages = messages; @@ -238,12 +252,8 @@ export class Remix { // error at the source and log it cleanly instead. this._attachWsErrorHandlers(); - try { - getVoiceManager(client); - logger.player("VoiceManager initialized."); - } catch (e) { - logger.warn("[VoiceManager] Init failed:", e.message); - } + // VoiceManager was already initialized before login (required for + // VOICE_STATES_SYNC event registration). No need to re-initialize here. const botId = client.user?.id ?? "0"; @@ -288,8 +298,7 @@ export class Remix { // The FluxerRevoice class provides the same .join() interface as // revoice.js's Revoice class, returning FluxerVoiceConnection objects // that wrap LiveKit Rooms compatible with revoice.js's MediaPlayer. - this.revoice = new FluxerRevoice(client); - logger.player("[FluxerRevoice] Instance created with Fluxer client."); + this.revoice = FluxerRevoice.getInstance(client); // ── Player Manager ─────────────────────────────────────────────────────── this.playerContext = { @@ -379,6 +388,19 @@ export class Remix { } catch (_) {} } + // Fallback: check LiveKit remote participants if guild cache is empty. + // This is the most reliable source of truth — if the bot's LiveKit room + // has remote participants, those are real humans in the channel. + if (!hasHuman) { + try { + const room = player.connection?.room; + if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) { + hasHuman = true; + logger.aloneCheck(`[AloneCheck] Found ${room.remoteParticipants.size} LiveKit remote participant(s) in ${channelId}`); + } + } catch (_) {} + } + logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`); if (!hasHuman && !player._paused) { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 421b30f..9e9263b 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -1,4 +1,5 @@ import { Events, GatewayOpcodes } from "@fluxerjs/core"; +import { getVoiceManager } from "@fluxerjs/voice"; import { logger } from "./constants/Logger.mjs"; import { ServerSettings } from "./Settings.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs"; @@ -39,6 +40,25 @@ export class GatewayHandler { // ── Previous voice state per-user (for detecting channel moves) ─────────── /** @type {Map} guildId:userId → state */ this._prevVoiceState = new Map(); + + // ── Recent join tracker (for detecting channel moves during recovery) ──── + // When the bot joins a new channel via recovery/spawn, the gateway sends + // a VOICE_STATE_UPDATE with channel_id=null for the old channel. Without + // tracking recent joins, this looks like a real disconnect and triggers + // a recovery loop. By tracking recent joins, we can distinguish between + // a real disconnect and a channel-move side effect. + /** @type {Map} guildId → timestamp of last bot voice join */ + this._recentBotJoins = new Map(); + /** @type {number} Window in ms during which a bot disconnect is considered + * a move side-effect rather than a real disconnect. */ + this._moveDetectionWindow = 10_000; + + // ── Gateway disconnect cooldown ────────────────────────────────────────── + // After the gateway force-disconnects the bot, don't attempt recovery + // for this guild until the cooldown expires. This prevents the cascade + // where recovery rejoins → gateway disconnects again → recovery again. + /** @type {Map} guildId → timestamp when cooldown expires */ + this._gatewayDisconnectCooldown = new Map(); } // ── Voice-state key helpers ────────────────────────────────────────────────── @@ -87,6 +107,52 @@ export class GatewayHandler { const { remix } = this; const client = remix.client; + // ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ──────────── + // The VoiceManager populates its voiceStates Map from VOICE_STATES_SYNC + // and VOICE_STATE_UPDATE gateway events. This is the most reliable source + // because it works regardless of whether guild.voice_states is populated + // by @fluxerjs/core (which it often isn't on Fluxer). + try { + const vm = getVoiceManager(client); + if (vm?.voiceStates) { + // voiceStates is a Map> + for (const [guildId, userMap] of vm.voiceStates) { + if (!userMap || typeof userMap.forEach !== "function") continue; + const cleanGuildId = String(guildId).replace(/\D/g, ""); + if (!cleanGuildId) continue; + userMap.forEach((channelId, userId) => { + if (!userId || !channelId) return; + // The bot's own ID is included in voiceStates — track it as a bot + const botId = client.user?.id; + if (userId === botId) { + const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId }); + } else { + // Check if this user is a bot via the members cache + const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); + const member = guild?.members?.get?.(userId); + const isBot = member?.user?.bot ?? false; + if (isBot) { + const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId }); + } else { + remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId }); + } + } + }); + } + logger.voiceState( + `[Seed] Seeded from VoiceManager.voiceStates — ` + + `${remix.observedVoiceUsers.size} humans, ${remix.observedVoiceBots.size} bots tracked.` + ); + return; // VoiceManager is the primary source — skip fallback + } + } catch (e) { + logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`); + } + + // ── Fallback: guild.voice_states cache ────────────────────────────────── + // Only used if VoiceManager is unavailable (shouldn't happen in normal ops). for (const [gId, guild] of client.guilds) { const voiceStatesRaw = guild.voice_states ?? @@ -146,29 +212,124 @@ export class GatewayHandler { if (!cleanGuild || !cleanChannel) return 0; let humansFound = 0; + const botId = client.user?.id; + // ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ──────────── + try { + const vm = getVoiceManager(client); + if (vm?.voiceStates) { + const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); + if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") { + guildVoiceMap.forEach((userChannelId, userId) => { + if (!userId || !userChannelId) return; + const userChannel = String(userChannelId).replace(/\D/g, ""); + if (userChannel !== cleanChannel) return; + if (userId === botId) { + const botKey = this.getObservedVoiceBotKey(userId, cleanGuild); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + } else { + const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); + const member = guild?.members?.get?.(userId); + const isBot = member?.user?.bot ?? false; + if (isBot) { + const botKey = this.getObservedVoiceBotKey(userId, cleanGuild); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + } else { + remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild }); + humansFound++; + logger.voiceState( + `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager` + ); + } + } + }); + + // Update the bot's own entry + if (botId) { + const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + } + + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.observedVoiceUsers.size}` + ); + + // If VoiceManager found humans, skip fallbacks + if (humansFound > 0) return humansFound; + } + } + } catch (e) { + logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`); + } + + // ── Fallback: guild.voice_states cache ────────────────────────────────── const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); if (!guild) { logger.voiceState( `[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.` ); - return 0; + } else { + const voiceStatesRaw = + guild.voice_states ?? + guild.voiceStates ?? + null; + + if (voiceStatesRaw) { + if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" + && typeof voiceStatesRaw.values !== "function") { + for (const [uid, val] of Object.entries(voiceStatesRaw)) { + const stateChannel = typeof val === "string" ? val + : val?.channelId ?? val?.channel_id ?? null; + if (!uid || !stateChannel) continue; + const isBot = val?.member?.user?.bot ?? false; + if (isBot) continue; + if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { + remix.observedVoiceUsers.set(uid, { channelId: stateChannel, guildId: cleanGuild }); + humansFound++; + logger.voiceState( + `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})` + ); + } + } + } else { + const entries = Array.isArray(voiceStatesRaw) + ? voiceStatesRaw + : [...voiceStatesRaw.values()]; + for (const state of entries) { + const userId = state?.userId ?? state?.user_id ?? state?.id; + const stateChannel = state?.channelId ?? state?.channel_id; + if (!userId || !stateChannel) continue; + const isBot = state?.member?.user?.bot ?? false; + if (isBot) continue; + if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { + remix.observedVoiceUsers.set(userId, { channelId: stateChannel, guildId: cleanGuild }); + humansFound++; + logger.voiceState( + `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})` + ); + } + } + } + + // Update bot's own entry + if (botId) { + const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); + if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + } + + if (humansFound > 0) { + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s), observedVoiceUsers size now ${remix.observedVoiceUsers.size}` + ); + return humansFound; + } + } } - const voiceStatesRaw = - guild.voice_states ?? - guild.voiceStates ?? - null; - - if (!voiceStatesRaw) { - // Fallback: use observedVoiceUsers as a data source when the guild's - // voice_states cache is not populated by @fluxerjs/core. This is common - // because the raw WS listener populates observedVoiceUsers from READY, - // GUILD_CREATE, and VOICE_STATE_UPDATE events, but the Guild object - // itself may not have a voice_states property. - logger.voiceState( - `[Reseed] Guild ${cleanGuild} has no voice_states cache — falling back to observedVoiceUsers.` - ); + // ── Fallback: observedVoiceUsers ──────────────────────────────────────── + if (humansFound === 0) { for (const [uid, info] of remix.observedVoiceUsers) { const infoGuild = String(info.guildId ?? "").replace(/\D/g, ""); const infoChannel = String(info.channelId ?? "").replace(/\D/g, ""); @@ -179,66 +340,33 @@ export class GatewayHandler { ); } } - // Also update the bot's own entry - const botId = client.user?.id; + + // Update bot's own entry if (botId) { const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); - if (botKey) { - remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); - } - } - logger.voiceState( - `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + - `found ${humansFound} human(s) via fallback, observedVoiceUsers size now ${remix.observedVoiceUsers.size}` - ); - return humansFound; - } - - // Process object-style voice_states (keyed by userId) - if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" - && typeof voiceStatesRaw.values !== "function") { - for (const [uid, val] of Object.entries(voiceStatesRaw)) { - const stateChannel = typeof val === "string" ? val - : val?.channelId ?? val?.channel_id ?? null; - if (!uid || !stateChannel) continue; - const isBot = val?.member?.user?.bot ?? false; - if (isBot) continue; - if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { - remix.observedVoiceUsers.set(uid, { channelId: stateChannel, guildId: cleanGuild }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})` - ); - } - } - } else { - // Process array / iterable style voice_states - const entries = Array.isArray(voiceStatesRaw) - ? voiceStatesRaw - : [...voiceStatesRaw.values()]; - for (const state of entries) { - const userId = state?.userId ?? state?.user_id ?? state?.id; - const stateChannel = state?.channelId ?? state?.channel_id; - if (!userId || !stateChannel) continue; - const isBot = state?.member?.user?.bot ?? false; - if (isBot) continue; - if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { - remix.observedVoiceUsers.set(userId, { channelId: stateChannel, guildId: cleanGuild }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})` - ); - } + if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); } } - // Also check the bot's own observed bots map — update the bot's entry - // so the voice state handler knows the bot is in this channel. - const botId = client.user?.id; - if (botId) { - const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); - if (botKey) { - remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + // ── Last resort: LiveKit remote participants ──────────────────────────── + if (humansFound === 0) { + try { + const player = remix.players.playerMap.get(cleanChannel); + const room = player?.connection?.room; + if (room?.isConnected && room.remoteParticipants) { + for (const [, participant] of room.remoteParticipants) { + const userId = participant?.identity ?? participant?.sid; + if (userId) { + humansFound++; + remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild }); + logger.voiceState( + `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants` + ); + } + } + } + } catch (e) { + logger.voiceState(`[Reseed] LiveKit participant fallback error: ${e?.message}`); } } @@ -451,20 +579,50 @@ export class GatewayHandler { if (!guildId) return; // Part 1: Voice state population - // Purge stale entries for this guild first. - for (const [uid, info] of [...remix.observedVoiceUsers]) { - if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) - remix.observedVoiceUsers.delete(uid); - } - for (const [uid, info] of [...remix.observedVoiceBots]) { - if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) - remix.observedVoiceBots.delete(uid); - } - + // Only purge stale entries if the GUILD_CREATE actually contains + // voice_states data. If voice_states is empty, the guild may just + // not provide voice state data in GUILD_CREATE (common on Fluxer), + // and purging would destroy data we collected from VOICE_STATE_UPDATE + // events. Only purge entries for users that appear in the new + // voice_states data (so we can replace them with fresh data). const voiceStatesRaw = guild.voice_states ?? guild.voiceStates ?? null; + + if (voiceStatesRaw) { + // Build a set of user IDs from the new voice_states data + const newUserIds = new Set(); + if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" + && typeof voiceStatesRaw.values !== "function") { + for (const uid of Object.keys(voiceStatesRaw)) { + newUserIds.add(uid); + } + } else { + const entries = Array.isArray(voiceStatesRaw) + ? voiceStatesRaw + : [...voiceStatesRaw.values()]; + for (const state of entries) { + const userId = state?.userId ?? state?.user_id ?? state?.id; + if (userId) newUserIds.add(userId); + } + } + + // Only purge entries for users that are being replaced by new data + for (const [uid, info] of [...remix.observedVoiceUsers]) { + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "") + && newUserIds.has(uid)) { + remix.observedVoiceUsers.delete(uid); + } + } + for (const [uid, info] of [...remix.observedVoiceBots]) { + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) { + const botKey = uid; // observedVoiceBots keys are "guildId:userId" + // Check if this bot entry is for the current guild + remix.observedVoiceBots.delete(uid); + } + } + } if (voiceStatesRaw) { if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" && typeof voiceStatesRaw.values !== "function") { @@ -751,6 +909,11 @@ export class GatewayHandler { // ── Bot-only logic below ─────────────────────────────────────────────── + // Track recent bot joins to distinguish real disconnects from move side-effects + if (channelId && guildId) { + this._recentBotJoins.set(String(guildId).replace(/\D/g, ""), Date.now()); + } + const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") ); @@ -779,17 +942,35 @@ export class GatewayHandler { let rekeyed = false; if (existingPlayer && cleanId !== cleanOld) { if (guildIsAmbiguous) { - // Multi-voice guild: can't safely re-key the playerMap (another player - // might already use cleanId), but still update the moved player's - // home channel so 24/7 recovery targets the right channel. - existingPlayer._channelId = cleanId; - existingPlayer._home247Channel = cleanId; - if (targetGuildId) existingPlayer._guildId = targetGuildId; - rekeyed = false; // keep false — don't touch playerMap keys - logger.voice247( - `[247] Updated player channel ${cleanOld} → ${cleanId} ` + - `(guild ${guildId} has ${guildPlayers.length} active players, skipped re-key)` - ); + // Multi-voice guild: we need to re-key the playerMap so that + // lookups by the new channelId work. First check that no OTHER + // player is already using the new channelId as its key. + const playerAtNewKey = remix.players.playerMap.get(cleanId); + if (playerAtNewKey && playerAtNewKey !== existingPlayer) { + // Another player already uses the new key — update the moved + // player's channel fields but don't re-key to avoid collision. + existingPlayer._channelId = cleanId; + existingPlayer._home247Channel = cleanId; + if (targetGuildId) existingPlayer._guildId = targetGuildId; + rekeyed = false; + logger.voice247( + `[247] Updated player channel ${cleanOld} → ${cleanId} ` + + `(guild ${guildId} has ${guildPlayers.length} active players, ` + + `new key occupied by another player — skipped re-key)` + ); + } else { + // Safe to re-key: no collision + remix.players.playerMap.delete(cleanOld); + remix.players.playerMap.set(cleanId, existingPlayer); + existingPlayer._channelId = cleanId; + existingPlayer._home247Channel = cleanId; + if (targetGuildId) existingPlayer._guildId = targetGuildId; + rekeyed = true; + logger.voice247( + `[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` + + `(guild ${guildId} has ${guildPlayers.length} active players)` + ); + } } else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) { // If there's no player for the old channel in playerMap, this is a // stale "move" from a pre-restart voice state — the bot was in @@ -880,6 +1061,7 @@ export class GatewayHandler { if (!channelId && oldChannelId && guildId) { try { const cleanOld = String(oldChannelId).replace(/\D/g, ""); + const cleanGuild = String(guildId).replace(/\D/g, ""); if (remix.intentionalLeaves.has(cleanOld)) { logger.voice247(`[247] Skipping rejoin for ${cleanOld} — intentional leave.`); } else { @@ -895,9 +1077,35 @@ export class GatewayHandler { return pChannel !== cleanOld && !p.leaving && !p._destroyed; }); - if (botInOtherChannel) { + // Also check if there was a recent bot join in this guild — if so, + // the disconnect is likely a side-effect of the channel move, not a + // real disconnect that needs recovery. + const recentJoin = this._recentBotJoins.get(cleanGuild) ?? 0; + const timeSinceJoin = Date.now() - recentJoin; + const isLikelyMoveSideEffect = timeSinceJoin < this._moveDetectionWindow; + + // Also check if there are pending spawns for this guild — if a + // spawnPlayer is in progress, the disconnect is expected. + const hasPendingSpawn = [...this.recoveryManager.pendingSpawns].some(([, entry]) => + String(entry.guildId).replace(/\D/g, "") === cleanGuild + ) || [...this.recoveryManager.scheduledSpawns].some(([, entry]) => + String(entry.guildId).replace(/\D/g, "") === cleanGuild + ); + + // Check gateway disconnect cooldown — if the gateway recently + // force-disconnected us, don't attempt recovery again immediately. + const cooldownExpiry = this._gatewayDisconnectCooldown.get(cleanGuild) ?? 0; + const inCooldown = Date.now() < cooldownExpiry; + + if (inCooldown) { logger.voice247( - `[247] Bot disconnected from ${cleanOld} but is still in another channel ` + + `[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` + + `gateway disconnect cooldown active (${Math.ceil((cooldownExpiry - Date.now()) / 1000)}s remaining).` + ); + } else if (botInOtherChannel || (isLikelyMoveSideEffect && !hasPendingSpawn)) { + const reason = botInOtherChannel ? "bot in other channel" : `recent join ${timeSinceJoin}ms ago (move side-effect)`; + logger.voice247( + `[247] Bot disconnected from ${cleanOld} but ${reason} ` + `in guild ${guildId} — skipping recovery (likely a channel move).` ); // Clean up the old player entry if it wasn't already removed @@ -906,6 +1114,11 @@ export class GatewayHandler { remix.players.playerMap.delete(cleanOld); try { oldPlayer.destroy(); } catch (_) {} } + } else if (hasPendingSpawn) { + logger.voice247( + `[247] Bot disconnected from ${cleanOld} in guild ${guildId} — ` + + `pending spawn in progress, skipping recovery to avoid race.` + ); } else { const set = remix.settingsMgr.getServer(guildId); const raw = set.get("stay_247"); @@ -921,6 +1134,19 @@ export class GatewayHandler { const player = remix.players.playerMap.get(cleanOld); if (player && !player.leaving) { logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery..."); + + // Set a gateway disconnect cooldown for this guild to + // prevent recovery cascades. If recovery rejoins and the + // gateway force-disconnects again, we don't want to + // immediately retry. + this._gatewayDisconnectCooldown.set(cleanGuild, Date.now() + 15_000); + // Auto-clear the cooldown after 30 seconds + setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000); + + // Mark the disconnect reason on the player for smarter recovery + player._lastDisconnectReason = "gateway"; + player._lastDisconnectTime = Date.now(); + if (typeof player._recoverConnection === "function") { player._recoverConnection(); } else { diff --git a/src/Player.mjs b/src/Player.mjs index 06f5da2..7fc5e3c 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -330,6 +330,10 @@ export default class Player extends EventEmitter { _playingNext = false; _isRecovering = false; startedPlaying = null; + + // Track last disconnect reason for smarter recovery + _lastDisconnectReason = null; // "401" | "gateway" | "unexpected" | null + _lastDisconnectTime = 0; // timestamp of last disconnect // searches Map with max-size eviction to prevent memory leak on busy servers. searches = new Map(); _searchMaxSize = 50; @@ -468,6 +472,29 @@ export default class Player extends EventEmitter { return cleanHome || null; } + /** + * Resolve the guild ID for this player, using the channel cache + * as a fallback if _guildId is not set. This is needed for + * guild-scoped gateway leave signals. + * @returns {string|null} + */ + _resolveGuildId() { + const cleanGuild = String(this._guildId ?? "").replace(/\D/g, ""); + if (cleanGuild) return cleanGuild; + + // Fallback: resolve from the channel object + try { + const channelId = this._channelId ?? this._home247Channel; + if (channelId) { + const ch = this.client?.channels?.get?.(channelId); + const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null; + if (fromChannel) return String(fromChannel).replace(/\D/g, ""); + } + } catch (_) {} + + return null; + } + // ═══════════════════════════════════════════════════════════════════════════ // Volume Restore // ═══════════════════════════════════════════════════════════════════════════ @@ -508,6 +535,36 @@ export default class Player extends EventEmitter { this.emit("autoleave"); return; } + + // ── 401 Permission-based recovery guard ────────────────────────────── + // If the last disconnect was due to a 401 Unauthorized error, don't + // keep retrying — 401 is a permission problem, not a transient failure. + // Retrying just creates more 401 errors and recovery loops. + // Instead, give up on recovery and let the 24/7 system schedule a + // delayed respawn with proper cooldown. + if (this._lastDisconnectReason === "401") { + const timeSinceDisconnect = Date.now() - this._lastDisconnectTime; + if (timeSinceDisconnect < 60_000) { + // Within 60 seconds of a 401 — don't attempt recovery. + // Let the 24/7 system handle reconnection with its own delay. + logger.warn( + `[Player] Skipping recovery for guild ${this._guildId} — ` + + `last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` + + `Delegating to 24/7 respawn system.` + ); + this._isRecovering = false; + this._recoveryPending = false; + this.emit("autoleave"); + return; + } + // If more than 60s have passed since the 401, try again — permissions + // may have been restored. + logger.player( + `[Player] 401 was ${timeSinceDisconnect / 1000}s ago — retrying recovery ` + + `(permissions may have been restored).` + ); + } + this._isRecovering = true; this._recoveryPending = true; @@ -522,8 +579,16 @@ export default class Player extends EventEmitter { return; } // Exponential backoff: 2s, 4s, 8s, 16s, 32s (was linear: 2s, 4s, 6s, 8s, 10s) - const backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000); - logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms)`); + // If last disconnect was a gateway force-disconnect, use longer backoff + // to avoid the recovery cascade where rejoining causes another disconnect. + let backoffMs; + if (this._lastDisconnectReason === "gateway") { + // Gateway force-disconnects need longer recovery time to avoid cascading + backoffMs = Math.min(5000 * Math.pow(2, this._recoveryAttempts - 1), 60_000); + } else { + backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000); + } + logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms, reason: ${this._lastDisconnectReason ?? "unknown"})`); await Utils.sleep(backoffMs); // re-check after await — player may have been destroyed during backoff @@ -571,8 +636,21 @@ export default class Player extends EventEmitter { try { const vm = getVoiceManager(this.client); if (vm && typeof vm.updateVoiceState === "function") { - vm.updateVoiceState(null, { self_deaf: false, self_mute: false }); - logger.mediaplayer(`[Player] Sent gateway leave signal before recovery rejoin`); + // IMPORTANT: Always use guild-scoped leave. An unscoped + // updateVoiceState(null, opts) disconnects ALL guilds' voice + // connections, causing cascading failures. + const guildIdForLeave = this._guildId ?? this._resolveGuildId(); + if (guildIdForLeave) { + try { + vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false }); + } catch (e1) { + // Older @fluxerjs/voice may not accept 3-arg form + try { vm.updateVoiceState(guildIdForLeave, null); } catch (e2) {} + } + logger.mediaplayer(`[Player] Sent guild-scoped gateway leave signal for guild ${guildIdForLeave} before recovery rejoin`); + } else { + logger.warn(`[Player] Cannot send guild-scoped leave — no guildId available. Skipping to avoid disconnecting all guilds.`); + } } } catch (e) { logger.warn(`[Player] Gateway leave signal failed: ${e?.message}`); @@ -585,7 +663,7 @@ export default class Player extends EventEmitter { } } - await Utils.sleep(2000); + await Utils.sleep(3000); if (this.leaving || this._destroyed) return; logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`); @@ -693,6 +771,27 @@ export default class Player extends EventEmitter { } } } catch (_) {} + + // ── LiveKit participant fallback ────────────────────────────────────── + // If the above methods didn't find any humans (e.g., because + // voice_states cache is empty and observedVoiceUsers hasn't been + // populated yet after a restart), check the LiveKit room's remote + // participants. This is the most reliable source of truth for who's + // actually in the voice channel, since LiveKit knows about every + // connected participant regardless of gateway cache state. + try { + const room = this.connection?.room; + if (room?.isConnected && room.remoteParticipants) { + for (const [, participant] of room.remoteParticipants) { + // Remote participants in the LiveKit room are humans (the bot is + // the local participant). If there's at least one, humans are present. + if (participant?.identity || participant?.sid) { + return true; + } + } + } + } catch (_) {} + return false; } @@ -1157,12 +1256,21 @@ export default class Player extends EventEmitter { try { this.connection.removeAllListeners(); } catch (_) {} try { await this.connection.disconnect(); } catch (_) {} - // Send gateway leave signal so the gateway knows we left. + // Send guild-scoped gateway leave signal so the gateway knows we left. // Without this, joinVoiceChannel() may not get VOICE_SERVER_UPDATE. + // IMPORTANT: Never use unscoped updateVoiceState(null, opts) — it + // disconnects ALL guilds' voice connections. try { const vm = getVoiceManager(this.client); if (vm && typeof vm.updateVoiceState === "function") { - vm.updateVoiceState(null, { self_deaf: false, self_mute: false }); + const guildIdForLeave = this._guildId ?? this._resolveGuildId(); + if (guildIdForLeave) { + try { + vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false }); + } catch (_) { + try { vm.updateVoiceState(guildIdForLeave, null); } catch (_2) {} + } + } } } catch (_) {} @@ -1187,12 +1295,21 @@ export default class Player extends EventEmitter { await this.connection.disconnect(); } catch (_) {} - // Send gateway leave signal for the old channel so the gateway - // processes the leave before we join a new/different channel. + // Send guild-scoped gateway leave signal for the old channel so the + // gateway processes the leave before we join a new/different channel. + // IMPORTANT: Never use unscoped updateVoiceState(null, opts) — it + // disconnects ALL guilds' voice connections. try { const vm = getVoiceManager(this.client); if (vm && typeof vm.updateVoiceState === "function") { - vm.updateVoiceState(null, { self_deaf: false, self_mute: false }); + const guildIdForLeave = this._guildId ?? this._resolveGuildId(); + if (guildIdForLeave) { + try { + vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false }); + } catch (_) { + try { vm.updateVoiceState(guildIdForLeave, null); } catch (_2) {} + } + } } } catch (_) {} @@ -1201,7 +1318,10 @@ export default class Player extends EventEmitter { try { this._revoice.deleteConnection(this._channelId); } catch (_) {} } - await Utils.sleep(500); + // Wait longer (1500ms instead of 500ms) to give the Fluxer gateway + // time to process the voice state leave before we join a new channel. + // 500ms was too short and caused 401 errors on the subsequent join. + await Utils.sleep(1500); this.connection = null; this._mediaPlayer = null; } @@ -1349,7 +1469,16 @@ export default class Player extends EventEmitter { return; } if (!this.leaving && !this._destroyed) { - logger.mediaplayer("[Player] Unexpected disconnect detected"); + // Detect the reason for the disconnect to make smarter recovery decisions + const room = connection.room; + const lastSignalErr = room?._lastSignalError; + if (lastSignalErr?.includes?.("401") || lastSignalErr?.includes?.("Unauthorized")) { + this._lastDisconnectReason = "401"; + } else { + this._lastDisconnectReason = "unexpected"; + } + this._lastDisconnectTime = Date.now(); + logger.mediaplayer(`[Player] Unexpected disconnect detected (reason: ${this._lastDisconnectReason})`); this._stopMediaPlayer() .catch(() => {}) .finally(() => this._recoverConnection()); @@ -1408,6 +1537,12 @@ export default class Player extends EventEmitter { const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; logger.error("[Player] Join failed:", e.message, causeStr); + // Track the disconnect reason for smarter recovery decisions + if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { + this._lastDisconnectReason = "401"; + this._lastDisconnectTime = Date.now(); + } + if (this.connection) { try { this.connection.disconnect(); } catch (_) {} this.connection = null; @@ -1482,6 +1617,8 @@ export default class Player extends EventEmitter { } this._recoveryPending = false; this._isRecovering = false; + this._recoveryAttempts = 0; + this._lastDisconnectReason = null; this.searches.clear(); if (this._workerPool) { diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index 28fe576..0ef5f51 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -24,7 +24,7 @@ export class RecoveryManager { aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, rejoin247Delay: timers.rejoin247Delay ?? 3_000, - recoveryStaggerMs: timers.recoveryStaggerMs ?? 2_000, + recoveryStaggerMs: timers.recoveryStaggerMs ?? 3_000, recoveryConcurrency: timers.recoveryConcurrency ?? 2, }; @@ -39,6 +39,10 @@ export class RecoveryManager { this.maxTransientRetries = remix.config.timers?.maxTransientRetries ?? 5; /** @type {number} Base delay multiplier for exponential backoff (ms) */ this.retryBaseDelay = remix.config.timers?.retryBaseDelay ?? 15_000; + /** @type {Map} Per-guild 401 failure count for circuit breaker */ + this._guild401Count = new Map(); + /** @type {number} Max 401 failures per guild before circuit breaker trips */ + this._guild401Max = 2; // ── Ready flags ─────────────────────────────────────────────────────────── this.botReady = false; @@ -331,6 +335,35 @@ export class RecoveryManager { // Atomic mutex check — blocks concurrent spawns for the same channel. if (remix.players.playerMap.has(cleanChannelId) || this.pendingSpawns.has(cleanChannelId)) return; + + // ── Duplicate player cleanup for same guild ────────────────────────── + // If there's already a player for a different channel in this guild + // that has the SAME _channelId (e.g. due to a stale playerMap entry + // from a previous failed recovery), clean it up before spawning. + // This prevents the "multiple players per guild" conflict that causes + // "skipped re-key" and gateway force-disconnects. + const cleanGuildId = String(guildId).replace(/\D/g, ""); + for (const [mapKey, existingPlayer] of remix.players.playerMap) { + if (existingPlayer._destroyed || existingPlayer.leaving) { + remix.players.playerMap.delete(mapKey); + try { existingPlayer.destroy(); } catch (_) {} + continue; + } + // Check if an existing player in this guild has the same channel ID + // as the one we're about to spawn (stale state from a move/recovery) + const existingChannelId = String(existingPlayer._channelId ?? mapKey).replace(/\D/g, ""); + const existingGuildId = String(existingPlayer._guildId ?? "").replace(/\D/g, ""); + if (existingGuildId === cleanGuildId && existingChannelId === cleanChannelId) { + logger.warn( + `[PlayerSpawn] Found existing player for channel ${cleanChannelId} ` + + `in guild ${cleanGuildId} (mapKey=${mapKey}) — destroying duplicate before spawning new player` + ); + remix.players.playerMap.delete(mapKey); + try { existingPlayer.leave().catch(() => {}); } catch (_) {} + try { existingPlayer.destroy(); } catch (_) {} + } + } + this.pendingSpawns.add(cleanChannelId); try { @@ -453,7 +486,6 @@ export class RecoveryManager { // ── Re-seed voice states for this channel ──────────────────────────── // After joining, the bot needs to know who's already in the channel. // The initial seedVoiceStatesFromGuilds() may have missed users because - // the guild cache wasn't fully populated at boot, or because Discord // sends voice states during GUILD_CREATE before the bot processes them. // This re-reads the guild's voice_states cache and updates the // observedVoiceUsers map so the bot detects humans already present. @@ -514,24 +546,67 @@ export class RecoveryManager { // If the bot was kicked while offline (or between retries), the 401 will // keep repeating. Verify the bot is still in the guild — if not, clean // up all state and skip retries entirely. - if (e.message?.includes("401 Unauthorized") && !remix.client.guilds.has(guildId)) { + // ── 401 Unauthorized handling with circuit breaker ───────────────── + if (e.message?.includes("401 Unauthorized")) { + const cleanGId = String(guildId).replace(/\D/g, ""); + + // Bot no longer in guild → clean up entirely + if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGId)) { + logger.warn( + `[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. ` + + `Cleaning up and skipping retries.` + ); + this.cleanStaleGuild(guildId, "401 and bot not in guild"); + return; + } + + // Guild-level circuit breaker: if this guild has hit the 401 threshold, + // stop retrying all channels in it during this recovery cycle. + const prev401 = this._guild401Count.get(cleanGId) ?? 0; + const new401 = prev401 + 1; + this._guild401Count.set(cleanGId, new401); + + if (new401 >= this._guild401Max) { + logger.warn( + `[PlayerSpawn] 401 circuit breaker tripped for guild ${cleanGId} ` + + `(${new401} failures ≥ ${this._guild401Max}). Skipping all further ` + + `retries for this guild in the current recovery cycle.` + ); + // Cancel any other scheduled spawns for this guild + for (const [chId, entry] of this.scheduledSpawns) { + if (String(entry.guildId).replace(/\D/g, "") === cleanGId) { + clearTimeout(entry.timer); + this.scheduledSpawns.delete(chId); + logger.warn(`[PlayerSpawn] Circuit breaker cancelled spawn for channel ${chId}`); + } + } + return; + } + + // First 401 in guild — log with context but don't retry + // (401 is permission-based, retrying immediately won't help) logger.warn( - `[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. ` + - `Cleaning up and skipping retries.` + `[PlayerSpawn] 401 Unauthorized for channel ${cleanChannelId} in guild ${cleanGId} ` + + `(${new401}/${this._guild401Max} before circuit breaker). ` + + `Bot is still in guild — permissions may have been revoked. ` + + `Skipping retry (401 is persistent, not transient).` ); - this.cleanStaleGuild(guildId, "401 and bot not in guild"); return; } // Retry if the failure is a transient LiveKit race (with max retries + backoff) - // NOTE: "401 Unauthorized" is NOT transient — it means missing permissions or - // bot kicked from guild. It is handled above by the guild membership check. - const isTransient = e.message?.includes("engine is closed") || + // IMPORTANT: 401 Unauthorized is NOT transient — it's a permission error + // that will keep failing. It's already handled above with the circuit + // breaker. The "signal failure" pattern is excluded here because it + // includes 401 errors (e.g. "engine: signal failure: client error: 401 + // Unauthorized") — retrying those just creates more 401 errors. + const isTransient = (e.message?.includes("engine is closed") || e.message?.includes("MediaPlayer after retry") || e.message?.includes("LiveKit connection timeout") || e.message?.includes("LiveKit failed") || - e.message?.includes("No room available") || - e.message?.includes("signal failure"); + e.message?.includes("No room available")) && + !e.message?.includes("401") && + !e.message?.includes("Unauthorized"); // Use the retryCount passed into spawnPlayer from scheduleSpawn's closure. const prevRetryCount = retryCount; @@ -738,6 +813,19 @@ export class RecoveryManager { if (filteredList.length === 0) return; + // ── Sort join list by guild ID ────────────────────────────────────────── + // Group channels by guild so that same-guild joins are dispatched + // sequentially rather than concurrently. This is critical because the + // Fluxer gateway needs time to process each voice state transition + // before the next one — concurrent same-guild joins cause 401 errors. + filteredList.sort((a, b) => { + const ga = String(a.guildId).replace(/\D/g, ""); + const gb = String(b.guildId).replace(/\D/g, ""); + if (ga !== gb) return ga.localeCompare(gb); + // Within the same guild, maintain original order + return 0; + }); + const startTime = Date.now(); logger.recovery( `[Recovery] Joining ${filteredList.length} session(s) ` + @@ -786,6 +874,8 @@ export class RecoveryManager { try { fs.unlinkSync(this.recoveryPath); } catch (_) {} } + // Reset 401 circuit breaker for next boot cycle + this._guild401Count.clear(); this._autoJoinRunning = false; this._autoJoinDone = true; } diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index b19c727..d9033f1 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -109,6 +109,11 @@ export class FluxerVoiceConnection extends EventEmitter { */ async disconnect() { if (this._destroyed) return; + // Mark this as an intentional disconnect so the RoomEvent.Disconnected + // handler knows not to trigger recovery + if (this._voice && this.channelId) { + this._voice.markIntentionalDisconnect(this.channelId); + } this._destroyed = true; this._connected = false; @@ -171,16 +176,78 @@ export class FluxerRevoice extends EventEmitter { // per guild eliminates this race condition. /** @type {Map} */ _guildJoinQueue = new Map(); - /** @type {number} Delay between consecutive guild joins (ms) */ - _guildJoinDelay = 1500; + /** @type {number} Delay between consecutive guild joins (ms) — increased from 3000 to 4000 + * to give the Fluxer gateway more time to clean up the previous voice session + * before we request a new one. 3000ms was too short and caused 401 errors when + * multiple channels in the same guild were joined in quick succession. + * The Fluxer gateway's Erlang backend needs time to process voice state + * transitions, and concurrent joins within the cleanup window cause + * the new LiveKit token to be rejected with 401 Unauthorized. */ + _guildJoinDelay = 4000; + + /** @type {Set} Channel IDs where disconnect is expected (bot-initiated) */ + _intentionalDisconnects = new Set(); + + /** @type {Map} Guild ID → timestamp of last successful join. + * Used to add an extra safety delay when the previous join in this guild + * was very recent (< 5 seconds), which is the window where 401 errors + * are most likely due to the gateway not having fully processed the + * previous session's voice state. */ + _guildLastJoinTime = new Map(); + + /** @type {number} Minimum time between guild joins (ms) — enforced on top of + * the per-join delay. If a new join is requested within this window, we + * wait the remaining time before proceeding. Increased from 5000 to 7000 + * because 5000ms was insufficient to prevent 401 errors when the bot + * re-joins a channel in the same guild quickly after a disconnect. */ + _guildMinJoinInterval = 7000; + + /** @type {Map} Guild IDs that recently had a 401 error. + * Used to add an even longer backoff before retrying joins in that guild. */ + _guild401Cooldown = new Map(); // guildId → timestamp when cooldown expires + + /** @type {FluxerRevoice|null} Singleton instance */ + static _instance = null; + + /** + * Get or create the singleton FluxerRevoice instance. + * @param {import("@fluxerjs/core").Client} client + * @returns {FluxerRevoice} + */ + static getInstance(client) { + if (!FluxerRevoice._instance) { + FluxerRevoice._instance = new FluxerRevoice(client); + } + return FluxerRevoice._instance; + } constructor(client) { super(); + if (FluxerRevoice._instance) { + logger.warn( + `[FluxerRevoice] Duplicate instance creation detected! ` + + `Use FluxerRevoice.getInstance() instead of new FluxerRevoice(). ` + + `Stack: ${new Error().stack?.split('\n').slice(2, 5).join(' | ')}` + ); + } else { + FluxerRevoice._instance = this; + } if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance"); this.client = client; logger.player("[FluxerRevoice] Instance created with Fluxer client."); } + /** + * Mark a channel as expecting an intentional disconnect so the + * RoomEvent.Disconnected handler does not trigger recovery. + * @param {string} channelId + */ + markIntentionalDisconnect(channelId) { + this._intentionalDisconnects.add(String(channelId)); + // Auto-clear after 10 seconds as safety net + setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000); + } + /** * Send a VOICE_STATE_UPDATE leave signal to the Fluxer gateway so it * knows the bot is no longer in the given channel. Without this, the @@ -190,21 +257,76 @@ export class FluxerRevoice extends EventEmitter { * * @param {string} channelId — The channel ID to leave */ - _leaveGateway(channelId) { + _leaveGateway(channelId, guildId = null) { try { const vm = getVoiceManager(this.client); - if (vm && typeof vm.updateVoiceState === "function") { - // Sending a VOICE_STATE_UPDATE with channel_id = null (or omitting - // the channel) tells the gateway the bot is leaving voice. - // Some @fluxerjs/voice versions accept null, others need undefined. - vm.updateVoiceState(null, { self_deaf: false, self_mute: false }); - logger.player(`[FluxerRevoice] Sent gateway leave signal for channel ${channelId}`); + if (!vm) return; + + const guildForLeave = guildId ?? this._resolveGuildForChannel(channelId); + + // ── Method 1: Use vm.leave(guildId) — the recommended API ────────── + // The VoiceManager's leave() method sends a VOICE_STATE_UPDATE with + // channel_id=null for the specified guild, which is the correct way + // to leave voice on Fluxer. This avoids the unscoped leave problem. + if (guildForLeave && typeof vm.leave === "function") { + try { + vm.leave(guildForLeave); + logger.player(`[FluxerRevoice] Sent gateway leave via vm.leave() for guild ${guildForLeave}`); + return; + } catch (e) { + logger.warn(`[FluxerRevoice] vm.leave() failed for guild ${guildForLeave}: ${e?.message}`); + } + } + + // ── Method 2: Use vm.leaveChannel(channelId) ────────────────────── + if (typeof vm.leaveChannel === "function") { + try { + vm.leaveChannel(channelId); + logger.player(`[FluxerRevoice] Sent gateway leave via vm.leaveChannel() for channel ${channelId}`); + return; + } catch (e) { + logger.warn(`[FluxerRevoice] vm.leaveChannel() failed for channel ${channelId}: ${e?.message}`); + } + } + + // ── Method 3: Use vm.updateVoiceState() as last resort ───────────── + if (typeof vm.updateVoiceState === "function") { + if (guildForLeave) { + // NEVER send an unscoped updateVoiceState(null, opts) because it + // tells the gateway to leave ALL guilds' voice channels, causing + // cascading disconnections across all active voice connections. + try { + vm.updateVoiceState(guildForLeave, null, { self_deaf: false, self_mute: false }); + logger.player(`[FluxerRevoice] Sent gateway leave via updateVoiceState() for guild ${guildForLeave}`); + return; + } catch (e1) { + try { vm.updateVoiceState(guildForLeave, null); return; } catch (e2) {} + } + } + logger.warn( + `[FluxerRevoice] Cannot send guild-scoped leave for channel ${channelId} — ` + + `skipping leave signal to avoid disconnecting all guilds.` + ); } } catch (e) { logger.warn(`[FluxerRevoice] Gateway leave signal failed for ${channelId}: ${e?.message}`); } } + /** + * Resolve the guild ID for a given channel ID from the client cache. + * @param {string} channelId + * @returns {string|null} + */ + _resolveGuildForChannel(channelId) { + try { + const ch = this.client.channels?.get?.(channelId); + return ch?.guildId ?? ch?.guild?.id ?? null; + } catch (_) { + return null; + } + } + /** * Fully tear down a stale FluxerVoiceConnection: disconnect the native * @fluxerjs/voice connection, close the LiveKit room, remove from the @@ -216,6 +338,8 @@ export class FluxerRevoice extends EventEmitter { async _destroyStaleConnection(channelId, existing) { // 1. Remove from map immediately so no other code can get this dead ref this.connections.delete(channelId); + // Mark as intentional so the LiveKit disconnect handler doesn't trigger recovery + this.markIntentionalDisconnect(channelId); // 2. Disconnect the native @fluxerjs/voice connection (sends gateway leave) if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") { @@ -244,10 +368,13 @@ export class FluxerRevoice extends EventEmitter { // This is critical: if the gateway still thinks we're in the channel, // the next joinVoiceChannel() won't receive VOICE_SERVER_UPDATE and // the rejoin will fail. - this._leaveGateway(channelId); + const staleGuildId = this._resolveGuildForChannel(channelId); + this._leaveGateway(channelId, staleGuildId); - // 6. Brief delay to let the gateway process the leave before we rejoin - await new Promise(r => setTimeout(r, 1500)); + // 6. Brief delay to let the gateway process the leave before we rejoin. + // Increased from 1500ms to 2000ms to give the Erlang gateway backend + // more time to clean up the previous voice session. + await new Promise(r => setTimeout(r, 2000)); } /** @@ -273,9 +400,37 @@ export class FluxerRevoice extends EventEmitter { if (guildId) { // Serialize: wait for any in-flight join for this guild to complete, - // then add a short delay before starting our join. + // then add a delay before starting our join. const prev = this._guildJoinQueue.get(guildId) ?? Promise.resolve(); - const ourTurn = prev.then(() => new Promise(r => setTimeout(r, this._guildJoinDelay))); + const ourTurn = prev.then(async () => { + // Wait the base guild join delay + await new Promise(r => setTimeout(r, this._guildJoinDelay)); + + // Additional safety: if this guild was joined very recently, wait + // until the minimum interval has elapsed. This prevents the rapid + // rejoin that causes 401 Unauthorized errors. + const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0; + const elapsed = Date.now() - lastJoin; + if (elapsed < this._guildMinJoinInterval) { + const extraWait = this._guildMinJoinInterval - elapsed; + logger.player( + `[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` + + `waiting additional ${extraWait}ms to avoid 401 race` + ); + await new Promise(r => setTimeout(r, extraWait)); + } + + // If this guild recently had a 401 error, wait for the cooldown + const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0; + const cooldownRemaining = cooldownExpiry - Date.now(); + if (cooldownRemaining > 0) { + logger.player( + `[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` + + `waiting ${cooldownRemaining}ms before attempting join` + ); + await new Promise(r => setTimeout(r, cooldownRemaining)); + } + }); this._guildJoinQueue.set(guildId, ourTurn); await ourTurn; } @@ -313,6 +468,9 @@ export class FluxerRevoice extends EventEmitter { throw new Error(`Channel not found: ${channelId}`); } + // Resolve the guild ID for this channel (used for guild-scoped leave signals) + const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null; + // Use @fluxerjs/voice to join the channel via the Fluxer gateway. // This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow // and creates a LiveKit connection with the returned credentials. @@ -320,6 +478,19 @@ export class FluxerRevoice extends EventEmitter { try { nativeConnection = await joinVoiceChannel(this.client, channel); } catch (e) { + // If the error is 401 Unauthorized, set a cooldown for this guild + // so subsequent join attempts wait longer before retrying. + if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { + const gId = channelGuildId ?? this._resolveGuildForChannel(channelId); + if (gId) { + // Set 45-second cooldown for this guild to prevent rapid 401 retries + this._guild401Cooldown.set(gId, Date.now() + 45_000); + logger.warn( + `[FluxerRevoice] 401 error for channel ${channelId} — ` + + `setting 45s cooldown for guild ${gId}` + ); + } + } throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`); } @@ -339,7 +510,6 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`); } - // If we couldn't get a room, the connection might be Discord-style // (non-LiveKit) which we don't support for music playback. if (!room) { try { await nativeConnection.disconnect(); } catch (_) {} @@ -404,6 +574,14 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`); + // Record the successful join time for this guild so future joins + // can enforce the minimum interval and avoid 401 races. + if (channelGuildId) { + this._guildLastJoinTime.set(channelGuildId, Date.now()); + // Clear any 401 cooldown for this guild since the join succeeded + this._guild401Cooldown.delete(channelGuildId); + } + // Create our FluxerVoiceConnection wrapper const connection = new FluxerVoiceConnection(channelId, this, { room, @@ -415,7 +593,10 @@ export class FluxerRevoice extends EventEmitter { // Player.mjs's connection.on("disconnect") etc. still work. room.on(RoomEvent.Disconnected, (reason) => { - logger.player(`[FluxerRevoice] Room disconnected: ${reason ?? "unknown"}`); + const isIntentional = this._intentionalDisconnects.has(String(channelId)); + const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); + logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`); + this._intentionalDisconnects.delete(String(channelId)); connection._connected = false; connection._destroyed = true; @@ -426,7 +607,7 @@ export class FluxerRevoice extends EventEmitter { // Send gateway leave signal so the gateway knows we're gone. // Without this, the gateway may still think the bot is in the channel // and won't send a fresh VOICE_SERVER_UPDATE on rejoin. - this._leaveGateway(channelId); + this._leaveGateway(channelId, channelGuildId); // Try to disconnect the native @fluxerjs/voice connection as well, // in case it still has resources open.