emailengine-app 2.72.3 → 2.72.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ const { BaseClient } = require('./base-client');
13
13
  const { oauth2Apps } = require('../oauth2-apps');
14
14
 
15
15
  const { Subconnection } = require('./imap/subconnection');
16
+ const { ReconnectBackoff } = require('./reconnect-backoff');
16
17
 
17
18
  const {
18
19
  normalizePath,
@@ -146,13 +147,13 @@ class IMAPClient extends BaseClient {
146
147
  // Current connection state
147
148
  this.state = 'connecting';
148
149
 
149
- // Reconnection tracking for capped exponential backoff
150
- this.reconnectRetries = 0;
151
- this.reconnectMaxDelay = 30000; // 30 seconds max delay
150
+ // Reconnection tracking for capped exponential backoff (failed setup path)
151
+ this.reconnectBackoff = new ReconnectBackoff({ baseDelay: 1000, maxDelay: 30000 });
152
152
 
153
- // Error reconnection tracking
154
- this.errorReconnectDelay = 2000;
155
- this.errorReconnectMaxDelay = 30000;
153
+ // Error-triggered reconnection tracking. Base 3000 preserves the old
154
+ // stored-delay curve, which multiplied its 2000 start by 1.5 before
155
+ // the first use (3000, 4500, ... capped at 30000)
156
+ this.errorReconnectBackoff = new ReconnectBackoff({ baseDelay: 3000, maxDelay: 30000 });
156
157
  this.reconnectTimer = null;
157
158
  }
158
159
 
@@ -539,7 +540,11 @@ class IMAPClient extends BaseClient {
539
540
 
540
541
  /**
541
542
  * Retrieves the current mailbox listing from the IMAP server
542
- * Compares with stored listing to detect new/deleted/renamed folders
543
+ * Compares with stored listing to detect new/deleted/renamed folders.
544
+ * NB! The returned array is the only carrier of the one-shot `isNew` flag
545
+ * (it is not persisted) - callers refreshing the listing to process folder
546
+ * changes must pass the result to processListing(), or use
547
+ * refreshAndProcessListing() which does both steps
543
548
  * @param {Object} options - Listing options
544
549
  * @param {Object} connectionOptions - Connection options
545
550
  * @returns {Array} Array of mailbox objects
@@ -583,9 +588,9 @@ class IMAPClient extends BaseClient {
583
588
  this.defaultDelimiter = inboxData.delimiter;
584
589
  }
585
590
 
586
- // ignore non-selectable folders
591
+ // ignore non-selectable folders (RFC 5258: \NonExistent implies \Noselect)
587
592
  listing = listing
588
- .filter(mailbox => !mailbox.flags.has('\\Noselect'))
593
+ .filter(mailbox => !mailbox.flags.has('\\Noselect') && !mailbox.flags.has('\\NonExistent'))
589
594
  .map(mailbox => {
590
595
  mailbox.noInferiors = mailbox.flags.has('\\Noinferiors');
591
596
  return mailbox;
@@ -661,56 +666,88 @@ class IMAPClient extends BaseClient {
661
666
  }
662
667
 
663
668
  /**
664
- * Refreshes the folder list and creates Mailbox instances for new folders
665
- * @returns {Set} Set of newly created mailbox instances that need syncing
669
+ * Registers Mailbox instances for previously unseen entries in a mailbox
670
+ * listing and runs the initial sync for them. Entries carrying the one-shot
671
+ * `isNew` flag from getCurrentListing() become Mailbox instances whose first
672
+ * sync emits the mailboxNew notification, so every listing refresh done to
673
+ * process folder changes must route its result through here (callers that
674
+ * only read the listing, like listMailboxes(), do not).
675
+ * Intentionally not guarded by `refreshingList`: it must also run when called
676
+ * from inside refreshFolderList()'s own sync loop.
677
+ * @param {Array} listing - Listing returned by getCurrentListing()
678
+ * @returns {Set} Set of newly created mailbox instances that were synced
666
679
  */
667
- async refreshFolderList() {
668
- if (this.refreshingList) {
669
- return;
670
- }
671
- this.refreshingList = true;
672
-
673
- try {
674
- let accountData = await this.accountObject.loadAccountData();
675
-
676
- // Get configured paths to monitor (default to all)
677
- const accountPaths = [].concat(accountData.path || '*');
678
- if (!accountPaths.length) {
679
- accountPaths.push('*');
680
- }
680
+ async processListing(listing) {
681
+ let accountData = await this.accountObject.loadAccountData();
681
682
 
682
- let listing = await this.getCurrentListing();
683
+ // Get configured paths to monitor (default to all)
684
+ const accountPaths = [].concat(accountData.path || '*');
685
+ if (!accountPaths.length) {
686
+ accountPaths.push('*');
687
+ }
683
688
 
684
- let syncNeeded = new Set();
685
- for (let entry of listing) {
686
- if (
687
- // previously unseen
688
- !this.mailboxes.has(normalizePath(entry.path))
689
- ) {
690
- // Apply filtering rules based on account configuration
691
- if (!accountPaths.includes('*')) {
692
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
693
- // ignore changes
694
- entry.syncDisabled = true;
695
- }
696
- } else if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
697
- // For Gmail, only monitor All Mail, Spam, and Trash folders
698
- // Other folders are just labels and covered by All Mail
689
+ let syncNeeded = new Set();
690
+ for (let entry of listing || []) {
691
+ if (
692
+ // previously unseen
693
+ !this.mailboxes.has(normalizePath(entry.path))
694
+ ) {
695
+ // Apply filtering rules based on account configuration
696
+ if (!accountPaths.includes('*')) {
697
+ if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
698
+ // ignore changes
699
699
  entry.syncDisabled = true;
700
700
  }
701
-
702
- let mailbox = new Mailbox(this, entry);
703
- this.mailboxes.set(normalizePath(entry.path), mailbox);
704
- syncNeeded.add(mailbox);
701
+ } else if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
702
+ // For Gmail, only monitor All Mail, Spam, and Trash folders
703
+ // Other folders are just labels and covered by All Mail
704
+ entry.syncDisabled = true;
705
705
  }
706
+
707
+ let mailbox = new Mailbox(this, entry);
708
+ this.mailboxes.set(normalizePath(entry.path), mailbox);
709
+ syncNeeded.add(mailbox);
706
710
  }
711
+ }
707
712
 
708
- // sync new mailboxes
709
- for (let mailbox of syncNeeded) {
710
- await mailbox.sync(true);
713
+ // sync new mailboxes
714
+ for (let mailbox of syncNeeded) {
715
+ if (this.mailboxes.get(normalizePath(mailbox.path)) !== mailbox) {
716
+ // A nested listing refresh (a new mailbox that itself went
717
+ // missing mid-sync re-lists the folders) already cleared this
718
+ // entry as deleted - do not sync a stale instance
719
+ continue;
711
720
  }
721
+ await mailbox.sync(true);
722
+ }
723
+
724
+ return syncNeeded;
725
+ }
726
+
727
+ /**
728
+ * Fetches a fresh mailbox listing and processes it: folder deletions are
729
+ * cleared by getCurrentListing() and newly found folders are registered
730
+ * and synced by processListing(). Use this instead of a bare
731
+ * getCurrentListing() call whenever the goal is to process folder changes
732
+ * @returns {Set} Set of newly created mailbox instances that were synced
733
+ */
734
+ async refreshAndProcessListing() {
735
+ let listing = await this.getCurrentListing();
736
+ return await this.processListing(listing);
737
+ }
738
+
739
+ /**
740
+ * Refreshes the folder list and creates Mailbox instances for new folders
741
+ * @returns {Set} Set of newly created mailbox instances that need syncing
742
+ */
743
+ async refreshFolderList() {
744
+ if (this.refreshingList) {
745
+ return;
746
+ }
747
+ this.refreshingList = true;
712
748
 
713
- return syncNeeded;
749
+ try {
750
+ return await this.refreshAndProcessListing();
714
751
  } finally {
715
752
  this.refreshingList = false;
716
753
  }
@@ -722,7 +759,7 @@ class IMAPClient extends BaseClient {
722
759
  * @returns {Object} Connection response
723
760
  */
724
761
  async connect() {
725
- if (this.isClosing || this.isClosed) {
762
+ if (this.isClosing || this.isClosed || this.paused) {
726
763
  return false;
727
764
  }
728
765
 
@@ -733,9 +770,25 @@ class IMAPClient extends BaseClient {
733
770
 
734
771
  let accountData = await this.accountObject.loadAccountData();
735
772
 
773
+ if (this.isClosing || this.isClosed || this.paused) {
774
+ // pause() or close() was called while account data was loading. No
775
+ // socket exists yet (imapClient.connect() below is what dials out,
776
+ // and ImapFlow itself has no closed-state check), so bail out
777
+ // without overwriting the paused/closed state
778
+ return false;
779
+ }
780
+
736
781
  // throws if connection fails
737
782
  let response = await imapClient.connect();
738
783
 
784
+ if (this.isClosing || this.isClosed || this.paused) {
785
+ // pause() or close() raced with the connection handshake. close()
786
+ // already closed this.imapClient (assigned before connect() was
787
+ // called), so skip the setup instead of marking the account as
788
+ // syncing and clobbering the paused state
789
+ return false;
790
+ }
791
+
739
792
  this.state = 'syncing';
740
793
  await this.setStateVal();
741
794
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
@@ -830,6 +883,47 @@ class IMAPClient extends BaseClient {
830
883
  return this.mailboxes.get(path);
831
884
  }
832
885
 
886
+ /**
887
+ * Checks whether a folder is present in the tracked listing, either by
888
+ * path or by special-use selector (subconnections can be configured with
889
+ * either form)
890
+ * @param {string} path - Folder path or special-use selector
891
+ * @returns {boolean} True when a tracked mailbox matches
892
+ */
893
+ hasListedMailbox(path) {
894
+ if (this.mailboxes.has(normalizePath(path))) {
895
+ return true;
896
+ }
897
+ if (!path.startsWith('\\')) {
898
+ // Special-use selectors always start with a backslash - a plain
899
+ // path that missed the map lookup can not match the fallback scan
900
+ return false;
901
+ }
902
+ for (let mailbox of this.mailboxes.values()) {
903
+ if (mailbox.listingEntry && mailbox.listingEntry.specialUse === path) {
904
+ return true;
905
+ }
906
+ }
907
+ return false;
908
+ }
909
+
910
+ /**
911
+ * Removes a client from connection tracking and persists the updated
912
+ * connection count. Used wherever a client goes away without its 'close'
913
+ * listener firing (listeners already removed, or no socket was ever
914
+ * opened). Never throws
915
+ * @param {Object} imapClient - Tracked ImapFlow instance
916
+ */
917
+ async untrackConnection(imapClient) {
918
+ if (this.connections.delete(imapClient)) {
919
+ try {
920
+ await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
921
+ } catch (err) {
922
+ this.logger.error({ msg: 'Failed to update connection count in Redis', err });
923
+ }
924
+ }
925
+ }
926
+
833
927
  /**
834
928
  * Handles an untagged EXISTS notification (new messages in a mailbox)
835
929
  * @param {Object} imapClient - IMAP connection that emitted the event
@@ -858,7 +952,10 @@ class IMAPClient extends BaseClient {
858
952
  if (!mailbox) {
859
953
  return;
860
954
  }
861
- await mailbox.onOpen(event);
955
+ // Pass the emitting client so the re-entrancy latch in onOpen()
956
+ // can tell a same-connection re-SELECT apart from an open event
957
+ // that arrived from a replacement connection after a reconnect
958
+ await mailbox.onOpen(event, imapClient);
862
959
  } catch (err) {
863
960
  if (err.code === 'IMAPConnectionClosing') {
864
961
  imapClient.log.debug({ msg: 'Open skipped, connection closing', err });
@@ -937,13 +1034,13 @@ class IMAPClient extends BaseClient {
937
1034
  this._connecting = true;
938
1035
  this.isClosed = false;
939
1036
 
940
- let accountData = await this.accountObject.loadAccountData();
941
- // Get indexing strategy for this account
942
- this.imapIndexer = typeof accountData.imapIndexer === 'string' && accountData.imapIndexer ? accountData.imapIndexer : 'full';
943
-
944
1037
  try {
945
1038
  this.logger.debug({ msg: 'Initiating connection to IMAP' });
946
- // Use exponential backoff for connection attempts
1039
+ // Use exponential backoff for connection attempts. Account data is
1040
+ // loaded inside start(), so a transient load failure (e.g. a Redis
1041
+ // hiccup) is retried by this loop - a throw that escaped past the
1042
+ // retry scheduling below used to stall the account until the next
1043
+ // external trigger
947
1044
  await backOff(() => this.start(), {
948
1045
  maxDelay: MAX_BACKOFF_DELAY,
949
1046
  numOfAttempts: Infinity,
@@ -983,34 +1080,36 @@ class IMAPClient extends BaseClient {
983
1080
  } catch (err) {
984
1081
  // ignore
985
1082
  }
1083
+
1084
+ // Reset reconnection backoff only after a fully successful setup.
1085
+ // syncMailboxes() can also return without throwing when the client
1086
+ // drops mid-sync, so gate the reset on a still-usable client.
1087
+ this.reconnectBackoff.reset();
1088
+ this.errorReconnectBackoff.reset();
986
1089
  }
987
1090
  } catch (err) {
988
1091
  // ended in an unconncted state
989
1092
  this.logger.warn({ msg: 'Failed to set up connection, will retry', err });
990
1093
 
991
1094
  // Calculate delay with capped exponential backoff
992
- const retryDelay = Math.min(this.reconnectMaxDelay, 1000 * Math.pow(1.5, Math.min(this.reconnectRetries, 10)));
993
- this.reconnectRetries++;
1095
+ const retryDelay = this.reconnectBackoff.nextDelay();
994
1096
 
995
1097
  this.logger.info({
996
1098
  msg: 'Scheduling reconnection attempt',
997
- attempt: this.reconnectRetries,
1099
+ attempt: this.reconnectBackoff.attempts,
998
1100
  delay: retryDelay
999
1101
  });
1000
1102
 
1001
1103
  return setTimeout(() => {
1002
- this.reconnect()
1003
- .then(() => {
1004
- // Reset counter on successful reconnect
1005
- this.reconnectRetries = 0;
1006
- })
1007
- .catch(err => {
1008
- this.logger.warn({
1009
- msg: 'Connection retry failed',
1010
- err,
1011
- attempt: this.reconnectRetries
1012
- });
1104
+ // The backoff counter is reset after a successful sync, not here -
1105
+ // reconnect() also resolves when the setup failed and was rescheduled
1106
+ this.reconnect().catch(err => {
1107
+ this.logger.warn({
1108
+ msg: 'Connection retry failed',
1109
+ err,
1110
+ attempt: this.reconnectBackoff.attempts
1013
1111
  });
1112
+ });
1014
1113
  }, retryDelay);
1015
1114
  }
1016
1115
 
@@ -1091,6 +1190,22 @@ class IMAPClient extends BaseClient {
1091
1190
  await this.redis.hdel(this.getAccountKey(), 'lastErrorState', 'lastError:errorCount', 'lastError:first');
1092
1191
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
1093
1192
 
1193
+ // Revive subconnections that disabled themselves while their monitored
1194
+ // folder was missing, once the folder shows up in the listing again.
1195
+ // setupSubConnections() is otherwise only invoked from start(), so on
1196
+ // a stable long-lived connection a re-created folder would never get
1197
+ // its subconnection back. Permanently disabled placeholders (covered
1198
+ // by the primary connection etc.) are left alone
1199
+ if (this.subconnections.some(subconnection => subconnection.mailboxMissing && this.hasListedMailbox(subconnection.path))) {
1200
+ this.setupSubConnections()
1201
+ .then(result => {
1202
+ this.logger.info({ msg: 'Reconciled subconnections after a folder change', account: this.account, result });
1203
+ })
1204
+ .catch(err => {
1205
+ this.logger.error({ msg: 'Failed to reconcile subconnections', account: this.account, err });
1206
+ });
1207
+ }
1208
+
1094
1209
  // Select main mailbox for IDLE monitoring
1095
1210
  let mainPath = this.main ? this.main.path : 'INBOX';
1096
1211
  if (this.mailbox && normalizePath(this.mailbox.path) === normalizePath(mainPath)) {
@@ -1341,6 +1456,10 @@ class IMAPClient extends BaseClient {
1341
1456
  if (prevImapClient === this.imapClient) {
1342
1457
  this.imapClient = null;
1343
1458
  }
1459
+
1460
+ // The close handler that maintains the connection count was removed
1461
+ // above, so update the tracking for the replaced client manually
1462
+ await this.untrackConnection(prevImapClient);
1344
1463
  }
1345
1464
  }
1346
1465
 
@@ -1351,6 +1470,9 @@ class IMAPClient extends BaseClient {
1351
1470
  this.notifyFrom = accountData.notifyFrom;
1352
1471
  this.syncFrom = accountData.syncFrom;
1353
1472
 
1473
+ // Get indexing strategy for this account
1474
+ this.imapIndexer = typeof accountData.imapIndexer === 'string' && accountData.imapIndexer ? accountData.imapIndexer : 'full';
1475
+
1354
1476
  if ((!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled)) {
1355
1477
  // can not make a connection
1356
1478
  this.state = 'unset';
@@ -1404,29 +1526,26 @@ class IMAPClient extends BaseClient {
1404
1526
  // Debounced reconnection with exponential backoff
1405
1527
  if (!this.reconnectTimer) {
1406
1528
  // Calculate delay with cap
1407
- this.errorReconnectDelay = Math.min(this.errorReconnectMaxDelay, this.errorReconnectDelay * 1.5);
1529
+ const errorRetryDelay = this.errorReconnectBackoff.nextDelay();
1408
1530
 
1409
1531
  this.logger.info({
1410
1532
  msg: 'Scheduling error-triggered reconnection',
1411
- delay: this.errorReconnectDelay
1533
+ delay: errorRetryDelay
1412
1534
  });
1413
1535
 
1414
1536
  this.reconnectTimer = setTimeout(() => {
1415
1537
  this.reconnectTimer = null;
1416
- this.reconnect()
1417
- .then(() => {
1418
- // Reset delay on success
1419
- this.errorReconnectDelay = 2000;
1420
- })
1421
- .catch(err => {
1422
- this.logger.warn({
1423
- msg: 'IMAP reconnection error',
1424
- account: this.account,
1425
- err,
1426
- nextDelay: this.errorReconnectDelay
1427
- });
1538
+ // The backoff delay is reset after a successful sync, not here -
1539
+ // reconnect() also resolves when the setup failed and was rescheduled
1540
+ this.reconnect().catch(err => {
1541
+ this.logger.warn({
1542
+ msg: 'IMAP reconnection error',
1543
+ account: this.account,
1544
+ err,
1545
+ attempt: this.errorReconnectBackoff.attempts
1428
1546
  });
1429
- }, this.errorReconnectDelay);
1547
+ });
1548
+ }, errorRetryDelay);
1430
1549
  }
1431
1550
  });
1432
1551
 
@@ -1443,15 +1562,7 @@ class IMAPClient extends BaseClient {
1443
1562
 
1444
1563
  // Handle connection close events
1445
1564
  imapClient.on('close', async () => {
1446
- const wasDeleted = this.connections.delete(imapClient);
1447
-
1448
- if (wasDeleted) {
1449
- try {
1450
- await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
1451
- } catch (err) {
1452
- this.logger.error({ msg: 'Failed to update connection count in Redis', err });
1453
- }
1454
- }
1565
+ await this.untrackConnection(imapClient);
1455
1566
  imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.disabled });
1456
1567
 
1457
1568
  // Update state on unexpected disconnect
@@ -1511,7 +1622,23 @@ class IMAPClient extends BaseClient {
1511
1622
 
1512
1623
  try {
1513
1624
  // Establish connection and perform initial sync
1514
- await this.connect();
1625
+ let connectResponse = await this.connect();
1626
+ if (connectResponse === false) {
1627
+ // connect() bailed out - the account was paused or closed
1628
+ // while the connection was being set up. Do not send success
1629
+ // notifications or set up subconnections for a connection
1630
+ // that was never established. NB! a successful connect()
1631
+ // resolves with undefined, so compare strictly
1632
+ this.logger.debug({ msg: 'Skipped post-connection setup', reason: 'connection not established' });
1633
+
1634
+ // The bailed client never opened a socket, so the 'close'
1635
+ // listener that maintains the connection count will not
1636
+ // fire - drop the tracking entry manually, otherwise a
1637
+ // paused account keeps reporting an active connection
1638
+ // (and holds the dormant client) until the next resume
1639
+ await this.untrackConnection(imapClient);
1640
+ return;
1641
+ }
1515
1642
 
1516
1643
  // Check if this is the first successful connection
1517
1644
  let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
@@ -1555,6 +1682,25 @@ class IMAPClient extends BaseClient {
1555
1682
  this.logger.error({ msg: 'Failed to set up subconnections', account: this.account, err });
1556
1683
  });
1557
1684
  } catch (err) {
1685
+ if (this.paused || this.isClosing || this.isClosed) {
1686
+ // pause()/close() interrupted the connection attempt.
1687
+ // ImapFlow rejects a pending connect() when the client is
1688
+ // closed, so the pause re-checks inside connect() never
1689
+ // run on this path. This is a requested shutdown, not a
1690
+ // connection error: sending a connectError webhook and
1691
+ // overwriting the freshly written 'paused' state here
1692
+ // would misreport a deliberately paused account
1693
+ this.logger.debug({
1694
+ msg: 'Skipped connection error handling',
1695
+ reason: 'connection attempt interrupted by pause or close',
1696
+ paused: this.paused,
1697
+ closing: this.isClosing,
1698
+ closed: this.isClosed,
1699
+ err
1700
+ });
1701
+ return;
1702
+ }
1703
+
1558
1704
  // Handle various authentication and connection errors
1559
1705
  if (err.oauthError && err.oauthError.status === 'invalid_request') {
1560
1706
  // access token is invalid, clear it
@@ -1630,6 +1776,12 @@ class IMAPClient extends BaseClient {
1630
1776
  clearTimeout(this.resyncTimer);
1631
1777
  clearTimeout(this.completedTimer);
1632
1778
  clearTimeout(this.reconnectTimer);
1779
+ // The error handler only schedules a debounced reconnection while
1780
+ // this.reconnectTimer is unset, and only the timer callback clears it.
1781
+ // A cleared-but-assigned handle would block error-triggered
1782
+ // reconnections for the rest of this instance's lifetime (resume()
1783
+ // reuses the instance), so drop the reference explicitly
1784
+ this.reconnectTimer = null;
1633
1785
 
1634
1786
  try {
1635
1787
  // Clean up all mailboxes
@@ -1680,6 +1832,9 @@ class IMAPClient extends BaseClient {
1680
1832
  clearTimeout(this.resyncTimer);
1681
1833
  clearTimeout(this.completedTimer);
1682
1834
  clearTimeout(this.reconnectTimer);
1835
+ // See delete() - a stale handle would permanently disable the
1836
+ // error-triggered reconnection debounce after pause()/resume()
1837
+ this.reconnectTimer = null;
1683
1838
 
1684
1839
  this.isClosing = false;
1685
1840
  this.isClosed = true;
@@ -2179,51 +2334,11 @@ class IMAPClient extends BaseClient {
2179
2334
 
2180
2335
  /**
2181
2336
  * Refreshes mailbox listing after account configuration changes
2182
- * @param {Object} accountData - Account data with path configuration
2183
2337
  */
2184
- runPostListing(accountData) {
2185
- const accountPaths = [].concat(accountData.path || '*');
2186
- if (!accountPaths.length) {
2187
- accountPaths.push('*');
2188
- }
2189
-
2190
- this.getCurrentListing()
2191
- .then(listing => {
2192
- let syncNeeded = new Set();
2193
- for (let entry of listing) {
2194
- if (
2195
- // previously unseen
2196
- !this.mailboxes.has(normalizePath(entry.path))
2197
- ) {
2198
- // Apply filtering based on account configuration
2199
- if (!accountPaths.includes('*')) {
2200
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
2201
- // ignore changes
2202
- entry.syncDisabled = true;
2203
- }
2204
- } else if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
2205
- // do not look for changes from this folder
2206
- entry.syncDisabled = true;
2207
- }
2208
-
2209
- let mailbox = new Mailbox(this, entry);
2210
- this.mailboxes.set(normalizePath(entry.path), mailbox);
2211
- syncNeeded.add(mailbox);
2212
- }
2213
- }
2214
-
2215
- let runSyncs = async () => {
2216
- // sync new mailboxes
2217
- for (let mailbox of syncNeeded) {
2218
- await mailbox.sync(true);
2219
- }
2220
- };
2221
-
2222
- return runSyncs();
2223
- })
2224
- .catch(err => {
2225
- this.logger.error({ msg: 'List refresh error', err });
2226
- });
2338
+ runPostListing() {
2339
+ this.refreshAndProcessListing().catch(err => {
2340
+ this.logger.error({ msg: 'List refresh error', err });
2341
+ });
2227
2342
  }
2228
2343
 
2229
2344
  /**
@@ -2278,8 +2393,7 @@ class IMAPClient extends BaseClient {
2278
2393
  }
2279
2394
 
2280
2395
  // Refresh listing to include new mailbox
2281
- let accountData = await this.accountObject.loadAccountData();
2282
- setImmediate(() => this.runPostListing(accountData));
2396
+ setImmediate(() => this.runPostListing());
2283
2397
 
2284
2398
  return result;
2285
2399
  } catch (err) {
@@ -2386,8 +2500,7 @@ class IMAPClient extends BaseClient {
2386
2500
  }
2387
2501
 
2388
2502
  // Refresh listing to update mailbox paths
2389
- let accountData = await this.accountObject.loadAccountData();
2390
- setImmediate(() => this.runPostListing(accountData));
2503
+ setImmediate(() => this.runPostListing());
2391
2504
 
2392
2505
  return result;
2393
2506
  }
@@ -2509,7 +2622,13 @@ class IMAPClient extends BaseClient {
2509
2622
  if (err.mailboxMissing) {
2510
2623
  // this mailbox is missing, refresh listing
2511
2624
  try {
2512
- await this.getCurrentListing(false, { connectionClient });
2625
+ let listing = await this.getCurrentListing(false, { connectionClient });
2626
+ // Register and sync newly found folders without delaying the
2627
+ // upload error response - the initial sync of a new folder
2628
+ // can take minutes
2629
+ this.processListing(listing).catch(listingErr => {
2630
+ this.logger.error({ msg: 'Failed to process listing', err: listingErr });
2631
+ });
2513
2632
  } catch (E) {
2514
2633
  this.logger.error({ msg: 'Missing mailbox', err, E });
2515
2634
  }
@@ -2542,6 +2661,40 @@ class IMAPClient extends BaseClient {
2542
2661
  * @returns {number|null} Number of subconnections created
2543
2662
  */
2544
2663
  async setupSubConnections() {
2664
+ if (this._settingUpSubConnections) {
2665
+ // A reconciliation run is already in flight (it can take a while -
2666
+ // each created subconnection dials out during init). Overlapping
2667
+ // runs would race the shared subconnections array, so defer this
2668
+ // request: the active run picks it up and executes one more pass
2669
+ // with the then-current state
2670
+ this._rerunSubConnections = true;
2671
+ return null;
2672
+ }
2673
+ this._settingUpSubConnections = true;
2674
+ try {
2675
+ let result = await this.processSubConnections();
2676
+ while (this._rerunSubConnections) {
2677
+ // A request arrived while the run above was in flight - the
2678
+ // config or listing may have changed since that run captured
2679
+ // its state, so reconcile once more instead of dropping it
2680
+ this._rerunSubConnections = false;
2681
+ result = await this.processSubConnections();
2682
+ }
2683
+ return result;
2684
+ } finally {
2685
+ this._settingUpSubConnections = false;
2686
+ this._rerunSubConnections = false;
2687
+ }
2688
+ }
2689
+
2690
+ /**
2691
+ * Reconciles the tracked subconnections against the account configuration
2692
+ * and the current folder listing. Internal worker for
2693
+ * setupSubConnections(), which holds the single-flight latch - never call
2694
+ * this directly
2695
+ * @returns {number|null} Number of tracked subconnections
2696
+ */
2697
+ async processSubConnections() {
2545
2698
  const accountData = await this.accountObject.loadAccountData();
2546
2699
 
2547
2700
  if (!accountData.subconnections?.length && !this.subconnections.length) {
@@ -2561,12 +2714,15 @@ class IMAPClient extends BaseClient {
2561
2714
  const entry = listing.find(entry => path === entry.path || path === entry.specialUse);
2562
2715
 
2563
2716
  if (!entry) {
2564
- // Mailbox not found - mark as disabled
2717
+ // Mailbox not found - mark as disabled. mailboxMissing is the
2718
+ // machine-readable marker consumed by the revival trigger in
2719
+ // syncMailboxes(); the disabledReason text is display copy
2565
2720
  mailboxes.push({
2566
2721
  path,
2567
2722
  disabled: true,
2568
2723
  state: 'disabled',
2569
- disabledReason: 'Mailbox folder not found'
2724
+ disabledReason: 'Mailbox folder not found',
2725
+ mailboxMissing: true
2570
2726
  });
2571
2727
  continue;
2572
2728
  }
@@ -2619,19 +2775,18 @@ class IMAPClient extends BaseClient {
2619
2775
  // remove unneeded subconnections
2620
2776
  for (let i = this.subconnections.length - 1; i >= 0; i--) {
2621
2777
  let subconnection = this.subconnections[i];
2622
- if (!mailboxes.find(mailbox => mailbox.path === subconnection.path)) {
2623
- // not listed anymore
2624
- this.subconnections.splice(i, 1);
2778
+ const mailbox = mailboxes.find(mailbox => mailbox.path === subconnection.path);
2625
2779
 
2626
- if (!subconnection.disabled) {
2627
- try {
2628
- subconnection.removeAllListeners();
2629
- subconnection.close();
2630
- } catch (err) {
2631
- this.logger.error({ msg: 'Failed to close unlisted subconnection', path: subconnection.path, err });
2632
- }
2633
- }
2780
+ if (mailbox && !mailbox.disabled === !subconnection.disabled) {
2781
+ // Still listed with the same active/disabled status - keep it
2782
+ continue;
2634
2783
  }
2784
+
2785
+ // Not listed anymore, or flipped between active and disabled (e.g.
2786
+ // the monitored folder was deleted or re-created). Drop the entry -
2787
+ // the create loop below adds the replacement where needed
2788
+ this.subconnections.splice(i, 1);
2789
+ this.closeSubconnection(subconnection);
2635
2790
  }
2636
2791
 
2637
2792
  // create missing subconnections
@@ -2691,6 +2846,24 @@ class IMAPClient extends BaseClient {
2691
2846
  return this.subconnections.length;
2692
2847
  }
2693
2848
 
2849
+ /**
2850
+ * Cleans up a single tracked subconnection entry. Disabled entries can be
2851
+ * placeholder objects without a close method, while a disabled live
2852
+ * instance still needs its listeners removed and its connection closed
2853
+ * @param {Subconnection|Object} subconnection - Live instance or placeholder
2854
+ */
2855
+ closeSubconnection(subconnection) {
2856
+ if (typeof subconnection.close !== 'function') {
2857
+ return;
2858
+ }
2859
+ try {
2860
+ subconnection.removeAllListeners();
2861
+ subconnection.close();
2862
+ } catch (err) {
2863
+ this.logger.error({ msg: 'Failed to close subconnection', path: subconnection.path, err });
2864
+ }
2865
+ }
2866
+
2694
2867
  /**
2695
2868
  * Closes all subconnections
2696
2869
  */
@@ -2699,14 +2872,7 @@ class IMAPClient extends BaseClient {
2699
2872
  this.subconnections = [];
2700
2873
 
2701
2874
  for (let subconnection of subconnections) {
2702
- if (!subconnection.disabled) {
2703
- try {
2704
- subconnection.removeAllListeners();
2705
- subconnection.close();
2706
- } catch (err) {
2707
- this.logger.error({ msg: 'Failed to close unlisted subconnection', path: subconnection.path, err });
2708
- }
2709
- }
2875
+ this.closeSubconnection(subconnection);
2710
2876
  }
2711
2877
  }
2712
2878