fix(discord): Fixed memory leak by repeated RPC failures (#4197)

This commit is contained in:
Iris
2026-01-29 09:05:19 +01:00
committed by GitHub
parent d2d6db192e
commit 7e4d1ab681

View File

@ -22,7 +22,7 @@ export class DiscordService {
/** /**
* Discord RPC client instance. * Discord RPC client instance.
*/ */
rpc = new DiscordClient({ clientId }); rpc!: DiscordClient;
/** /**
* Indicates if the service is ready to send activity updates. * Indicates if the service is ready to send activity updates.
*/ */
@ -62,6 +62,21 @@ export class DiscordService {
this.mainWindow = mainWindow; this.mainWindow = mainWindow;
this.autoReconnect = config?.autoReconnect ?? true; // Default autoReconnect to true this.autoReconnect = config?.autoReconnect ?? true; // Default autoReconnect to true
this.initializeRpc();
}
private initializeRpc() {
if (this.rpc) {
try {
this.rpc.destroy();
} catch {
// ignored
}
this.rpc.removeAllListeners();
}
this.rpc = new DiscordClient({ clientId });
this.rpc.on('connected', () => { this.rpc.on('connected', () => {
if (dev()) { if (dev()) {
console.log(LoggerPrefix, t('plugins.discord.backend.connected')); console.log(LoggerPrefix, t('plugins.discord.backend.connected'));
@ -192,6 +207,7 @@ export class DiscordService {
resolve(); resolve();
}) })
.catch(() => { .catch(() => {
this.initializeRpc();
this.connectRecursive(); this.connectRecursive();
}); });
}, },
@ -236,6 +252,9 @@ export class DiscordService {
this.resetInfo(); this.resetInfo();
if (this.autoReconnect) { if (this.autoReconnect) {
// For some reason @xhayper/discord-rpc leaves a dangling listener on connection failure
// so we destroy and recreate the RPC client before reconnecting.
this.initializeRpc();
this.connectRecursive(); this.connectRecursive();
} else if (showErrorDialog && this.mainWindow) { } else if (showErrorDialog && this.mainWindow) {
// connection failed // connection failed
@ -250,12 +269,11 @@ export class DiscordService {
this.autoReconnect = false; this.autoReconnect = false;
this.timerManager.clear(TimerKey.DiscordConnectRetry); this.timerManager.clear(TimerKey.DiscordConnectRetry);
this.timerManager.clear(TimerKey.ClearActivity); this.timerManager.clear(TimerKey.ClearActivity);
if (this.rpc.isConnected) { try {
try { this.rpc.removeAllListeners();
this.rpc.destroy(); this.rpc.destroy();
} catch { } catch {
// ignored // ignored
}
} }
this.resetInfo(); // Reset internal state this.resetInfo(); // Reset internal state
} }