From 7135cbb629ff3dc74a7ec8f5acf5ea211528136d Mon Sep 17 00:00:00 2001 From: Tero Date: Wed, 7 Oct 2026 00:00:30 +0300 Subject: [PATCH] Add persistent IMAP IDLE watchers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- TODO.md | 2 +- desktop/main.cjs | 98 ++++++++++++++++++++++++++++++++++++++++++++++- package-lock.json | 4 +- package.json | 2 +- 4 files changed, 100 insertions(+), 6 deletions(-) diff --git a/TODO.md b/TODO.md index b3c17b8..1c5a145 100644 --- a/TODO.md +++ b/TODO.md @@ -24,7 +24,7 @@ - [x] Fix automatic mail sync so the message list refreshes when new mail arrives. - [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background. - [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable. - - [ ] Add persistent IMAP IDLE watchers; bounded periodic polling currently provides updates and reconnect/backoff. + - [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support. - [ ] Add push mail support. - [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed. - [x] Send updates to the renderer over IPC and show native notifications for new inbox mail. diff --git a/desktop/main.cjs b/desktop/main.cjs index be98098..64e3143 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -12,12 +12,14 @@ const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.e const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); const backgroundSyncIntervalMs = 2 * 60 * 1000; const backgroundSyncConcurrency = 2; +const backgroundIdleConcurrency = 2; let accountStoreQueue = Promise.resolve(); let backgroundSyncInProgress = false; let backgroundSyncRequested = false; const backgroundSyncGenerations = new Map(); const backgroundSyncFailures = new Map(); const flagSnapshots = new Map(); +const idleWatchers = new Map(); function updateAccountStore(update) { const operation = accountStoreQueue.then(async () => { @@ -48,6 +50,7 @@ function requestBackgroundSync(accountId = null, force = false) { if (force) { for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0; } + void reconcileIdleWatchers().catch(error => console.error('Could not reconcile IMAP IDLE watchers:', error)); if (backgroundSyncInProgress) { if (accountId || force) backgroundSyncRequested = true; return; @@ -56,6 +59,89 @@ function requestBackgroundSync(accountId = null, force = false) { void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error)); } +function stopIdleWatcher(accountId) { + const watcher = idleWatchers.get(accountId); + if (!watcher) return; + watcher.stopped = true; + watcher.client?.close(); + idleWatchers.delete(accountId); +} + +function startIdleWatcher(account) { + if (idleWatchers.has(account.id)) return; + const watcher = { + generation: backgroundSyncGenerations.get(account.id) || 0, + stopped: false, + client: null + }; + idleWatchers.set(account.id, watcher); + void runIdleWatcher(account.id, watcher).catch(error => { + console.error(`IMAP IDLE watcher failed for ${account.email}:`, error); + }); +} + +async function runIdleWatcher(accountId, watcher) { + let failures = 0; + while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) { + let client; + try { + const account = await readAccount(accountId); + if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return; + client = imapClient(account, { + autoIdleDelay: 10_000, + maxIdleTime: 25 * 60 * 1000, + socketTimeout: 30 * 60 * 1000 + }); + watcher.client = client; + let signalDisconnected; + const disconnected = new Promise(resolve => { signalDisconnected = resolve; }); + client.on('exists', event => { + if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestBackgroundSync(); + }); + client.on('flags', event => { + if (event.path.toLowerCase() === 'inbox') requestBackgroundSync(); + }); + client.on('error', error => { + if (!watcher.stopped) console.error(`IMAP IDLE connection failed for ${account.email}:`, error); + signalDisconnected(); + }); + client.once('close', signalDisconnected); + await client.connect(); + if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return; + await client.mailboxOpen('INBOX', { readOnly: true }); + const connectedAt = Date.now(); + await disconnected; + if (Date.now() - connectedAt > 60_000) failures = 0; + } catch (error) { + if (!watcher.stopped) console.error(`IMAP IDLE watcher disconnected for ${accountId}:`, error); + } finally { + if (watcher.client === client) watcher.client = null; + if (client?.usable) await client.logout().catch(() => client.close()); + else client?.close(); + } + + if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return; + const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5))); + failures += 1; + await new Promise(resolve => { + const timer = setTimeout(resolve, retryDelay); + timer.unref(); + }); + } +} + +async function reconcileIdleWatchers() { + const store = (await readAccountStore()) || { accounts: [] }; + const desiredAccounts = store.accounts.slice(0, backgroundIdleConcurrency); + const desiredIds = new Set(desiredAccounts.map(account => account.id)); + for (const [accountId, watcher] of idleWatchers) { + if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) { + stopIdleWatcher(accountId); + } + } + for (const account of desiredAccounts) startIdleWatcher(account); +} + async function readDavStore() { try { const encrypted = await fs.readFile(davCredentialsPath()); @@ -118,7 +204,7 @@ function normalizeAccount(input) { return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 }; } -function imapClient(account) { +function imapClient(account, options = {}) { return new ImapFlow({ host: account.imapHost, port: account.imapPort, @@ -129,7 +215,8 @@ function imapClient(account) { logger: false, connectionTimeout: 15000, greetingTimeout: 10000, - socketTimeout: 20000 + socketTimeout: 20000, + ...options }); } @@ -848,6 +935,9 @@ app.whenReady().then(() => { const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs); syncTimer.unref(); requestBackgroundSync(); + powerMonitor.on('suspend', () => { + for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId); + }); powerMonitor.on('resume', () => requestBackgroundSync(null, true)); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); @@ -857,3 +947,7 @@ app.whenReady().then(() => { app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); + +app.on('before-quit', () => { + for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId); +}); diff --git a/package-lock.json b/package-lock.json index de0685c..7dbe89e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.1.15", + "version": "0.1.16", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.1.15", + "version": "0.1.16", "dependencies": { "ical.js": "^2.2.1", "imapflow": "2.2.1", diff --git a/package.json b/package.json index 58971a3..191de7d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.1.15", + "version": "0.1.16", "private": true, "description": "Eternity Project mail client", "author": "Eternity Project",