fix: dispose background notification clients (#1628)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fix background notification clients surviving disable, unmount, or a
superseded effect run.

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-08-06 14:48:26 +00:00
commit 9d1e7abef0
1 file changed
+45 -17
@@ -100,8 +100,13 @@ const startBackgroundClient = async (session: Session): Promise<MatrixClient> =>
timelineLimit: 1,
};
await startClient(mx, startOpts);
return mx;
try {
await startClient(mx, startOpts);
return mx;
} catch (error) {
stopClient(mx);
throw error;
}
};
/**
@@ -207,7 +212,9 @@ export function BackgroundNotifications() {
}
const { current } = clientsRef;
let disposed = false;
const activeIds = new Set(inactiveSessions.map((s) => s.userId));
const retryTimers: ReturnType<typeof setTimeout>[] = [];
async function sendNotification(opts: NotifyOptions): Promise<void> {
if (isDesktopTauri()) {
@@ -285,15 +292,27 @@ export function BackgroundNotifications() {
// Using a named function (vs. inline .then) lets the .catch() schedule a
// fresh retry referencing the latest session from inactiveSessionsRef.
const startSession = (session: Session, attempt = 0): void => {
if (disposed || current.has(session.userId)) return;
let sessionMx: MatrixClient | undefined;
startBackgroundClient(session)
.then(async (mx) => {
sessionMx = mx;
if (disposed) {
stopClient(mx);
return;
}
current.set(session.userId, mx);
Sentry.metrics.gauge('sable.background.client_count', current.size);
await waitForSync(mx);
if (disposed) return;
if (current.get(session.userId) !== mx) {
stopClient(mx);
return;
}
// Wait for m.direct account data to load. This is critical for DM detection.
// Without it, rooms in /direct/ won't be recognized as DMs, causing notifications to fail.
let mDirectsSet: Set<string> | undefined;
@@ -317,6 +336,12 @@ export function BackgroundNotifications() {
});
}
if (disposed) return;
if (current.get(session.userId) !== mx) {
stopClient(mx);
return;
}
const pushProcessor = mx.pushProcessor;
const handleAccountData = (event: MatrixEvent) => {
@@ -564,6 +589,7 @@ export function BackgroundNotifications() {
});
})
.catch((err) => {
if (disposed) return;
log.error('failed to start background client for', session.userId, err);
debugLog.error('notification', 'Failed to start background client', {
userId: session.userId,
@@ -585,14 +611,17 @@ export function BackgroundNotifications() {
// Retry with exponential backoff, up to 5 attempts (5s, 10s, 20s, 40s, 60s cap).
if (attempt < 5) {
const retryDelay = Math.min(5_000 * 2 ** attempt, 60_000);
setTimeout(() => {
const latestSession = inactiveSessionsRef.current.find(
(s) => s.userId === session.userId
);
if (latestSession && !current.has(session.userId)) {
startSession(latestSession, attempt + 1);
}
}, retryDelay);
retryTimers.push(
setTimeout(() => {
if (disposed) return;
const latestSession = inactiveSessionsRef.current.find(
(s) => s.userId === session.userId
);
if (latestSession && !current.has(session.userId)) {
startSession(latestSession, attempt + 1);
}
}, retryDelay)
);
}
});
};
@@ -610,16 +639,15 @@ export function BackgroundNotifications() {
});
const cleanupMap = clientCleanupRef.current;
const activeUserIds = new Set(inactiveSessions.map((s) => s.userId));
return () => {
disposed = true;
staggerTimers.forEach(clearTimeout);
retryTimers.forEach(clearTimeout);
current.forEach((mx, userId) => {
if (!activeUserIds.has(userId)) {
cleanupMap.get(userId)?.();
cleanupMap.delete(userId);
stopClient(mx);
current.delete(userId);
}
cleanupMap.get(userId)?.();
cleanupMap.delete(userId);
stopClient(mx);
current.delete(userId);
});
};
}, [