emailengine-app 2.73.1 → 2.74.1

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.
@@ -33,7 +33,15 @@ const RESYNC_DELAY = 15 * 60;
33
33
  // TTL for ensuring main mailbox selection after operations (5 seconds)
34
34
  const ENSURE_MAIN_TTL = 5 * 1000;
35
35
 
36
- const { AUTH_ERROR_NOTIFY, AUTH_SUCCESS_NOTIFY, CONNECT_ERROR_NOTIFY, DEFAULT_DOWNLOAD_CHUNK_SIZE, MAX_BACKOFF_DELAY, TLS_DEFAULTS } = require('../consts');
36
+ const {
37
+ AUTH_ERROR_NOTIFY,
38
+ AUTH_SUCCESS_NOTIFY,
39
+ CONNECT_ERROR_NOTIFY,
40
+ DEFAULT_DOWNLOAD_CHUNK_SIZE,
41
+ MAX_BACKOFF_DELAY,
42
+ STABLE_CONNECTION_TIME,
43
+ TLS_DEFAULTS
44
+ } = require('../consts');
37
45
 
38
46
  // Configuration for download operations - chunk size for streaming attachments/messages
39
47
  const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
@@ -155,6 +163,63 @@ class IMAPClient extends BaseClient {
155
163
  // the first use (3000, 4500, ... capped at 30000)
156
164
  this.errorReconnectBackoff = new ReconnectBackoff({ baseDelay: 3000, maxDelay: 30000 });
157
165
  this.reconnectTimer = null;
166
+
167
+ // Unexpected-close reconnection throttle. Deliberately NOT reset after
168
+ // a successful sync like the two backoffs above - a connection only
169
+ // validates it by surviving STABLE_CONNECTION_TIME. A server that
170
+ // accepts the full connection setup and then drops the connection
171
+ // would otherwise reset the delay on every cycle and loop at full
172
+ // speed (measured ~17 logins/sec against such a server). Jitter keeps
173
+ // a fleet of accounts on one failing host from reconnecting in sync
174
+ this.closeReconnectBackoff = new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
175
+ }
176
+
177
+ /**
178
+ * Checks whether a dropped connection had proven itself stable by
179
+ * surviving STABLE_CONNECTION_TIME, resetting the survival-gated close
180
+ * backoff when it had. Both the error and the close handler consult this,
181
+ * so a server that accepts the full connection setup and then drops the
182
+ * connection gets throttled the same way regardless of whether the drop
183
+ * surfaces as an error event or a bare close - the other backoffs are
184
+ * reset by a completed setup, which such a server passes on every cycle
185
+ * @param {Object} imapClient - The dropped connection
186
+ * @returns {Boolean} True when the connection had proven itself stable
187
+ */
188
+ validateConnectionAge(imapClient) {
189
+ if (Date.now() - imapClient.connectionStartTime >= STABLE_CONNECTION_TIME) {
190
+ this.closeReconnectBackoff.reset();
191
+ return true;
192
+ }
193
+ return false;
194
+ }
195
+
196
+ /**
197
+ * Schedules a debounced reconnection attempt. Shared by the error and
198
+ * close handlers - both draw from the single reconnectTimer slot, so
199
+ * whichever fires first owns the retry
200
+ * @param {Object} backoff - ReconnectBackoff instance that provides the delay
201
+ * @param {String} msg - Log message for the scheduling entry
202
+ */
203
+ scheduleReconnect(backoff, msg) {
204
+ if (this.reconnectTimer) {
205
+ return;
206
+ }
207
+ const retryDelay = backoff.nextDelay();
208
+ this.logger.info({ msg, account: this.account, attempt: backoff.attempts, delay: Math.round(retryDelay) });
209
+ this.reconnectTimer = setTimeout(() => {
210
+ this.reconnectTimer = null;
211
+ // The backoff counter is reset after a successful sync (or for the
212
+ // close backoff by proven connection survival), not here -
213
+ // reconnect() also resolves when the setup failed and was rescheduled
214
+ this.reconnect().catch(err => {
215
+ this.logger.warn({
216
+ msg: 'IMAP reconnection error',
217
+ account: this.account,
218
+ err,
219
+ attempt: backoff.attempts
220
+ });
221
+ });
222
+ }, retryDelay);
158
223
  }
159
224
 
160
225
  /**
@@ -1490,6 +1555,10 @@ class IMAPClient extends BaseClient {
1490
1555
  expungeHandler: async payload => await this.expungeHandler(payload)
1491
1556
  })
1492
1557
  );
1558
+ // Birth time of this connection attempt - the unexpected-close
1559
+ // handler uses the age to tell a stable connection dropping from a
1560
+ // connect/drop cycle that needs throttling
1561
+ imapClient.connectionStartTime = Date.now();
1493
1562
  this.connections.add(imapClient);
1494
1563
  await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
1495
1564
 
@@ -1523,29 +1592,14 @@ class IMAPClient extends BaseClient {
1523
1592
  }
1524
1593
  imapClient.close(); // ensure the client is closed on errors
1525
1594
 
1526
- // Debounced reconnection with exponential backoff
1527
- if (!this.reconnectTimer) {
1528
- // Calculate delay with cap
1529
- const errorRetryDelay = this.errorReconnectBackoff.nextDelay();
1530
-
1531
- this.logger.info({
1532
- msg: 'Scheduling error-triggered reconnection',
1533
- delay: errorRetryDelay
1534
- });
1535
-
1536
- this.reconnectTimer = setTimeout(() => {
1537
- this.reconnectTimer = null;
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
1546
- });
1547
- });
1548
- }, errorRetryDelay);
1595
+ if (this.validateConnectionAge(imapClient)) {
1596
+ // Transient error on a proven-stable connection
1597
+ this.scheduleReconnect(this.errorReconnectBackoff, 'Scheduling error-triggered reconnection');
1598
+ } else {
1599
+ // The connection died soon after it was set up - use the
1600
+ // survival-gated backoff, the error backoff is reset by
1601
+ // every completed setup and would never grow here
1602
+ this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1549
1603
  }
1550
1604
  });
1551
1605
 
@@ -1610,8 +1664,22 @@ class IMAPClient extends BaseClient {
1610
1664
  try {
1611
1665
  // Attempt reconnection if this was an unexpected close
1612
1666
  if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
1613
- imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1614
- await this.reconnect();
1667
+ if (this.validateConnectionAge(imapClient)) {
1668
+ // A proven-stable connection dropped - reconnect right away
1669
+ if (!this.reconnectTimer) {
1670
+ imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1671
+ await this.reconnect();
1672
+ }
1673
+ } else {
1674
+ // The connection died soon after it was set up. An
1675
+ // immediate retry against a server that drops
1676
+ // connections right after setup turns into an
1677
+ // unthrottled login loop (the setup itself
1678
+ // "succeeds", so the sync-reset backoffs never
1679
+ // grow), so schedule the reconnect with a growing
1680
+ // delay instead
1681
+ this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1682
+ }
1615
1683
  }
1616
1684
  } catch (err) {
1617
1685
  imapClient.log.error({ msg: 'Reconnection error', err });
@@ -1711,17 +1779,22 @@ class IMAPClient extends BaseClient {
1711
1779
  }
1712
1780
  }
1713
1781
 
1782
+ // ImapFlow rewrites err.response into a string for authentication
1783
+ // failures, but for other command failures it is the parsed response
1784
+ // object - prefer the response text so the stored error state and
1785
+ // webhook payloads never render as "[object Object]"
1786
+ let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1714
1787
  if (err.authenticationFailed) {
1715
1788
  this.logger.error({ msg: 'Failed to authenticate', account: this.account, err });
1716
1789
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1717
- response: err.response,
1790
+ response: errorResponse,
1718
1791
  serverResponseCode: err.serverResponseCode
1719
1792
  });
1720
1793
  this.state = 'authenticationError';
1721
1794
  } else {
1722
1795
  this.logger.error({ msg: 'Failed to connect', account: this.account, err });
1723
1796
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
1724
- response: err.response || err.message,
1797
+ response: errorResponse || err.message,
1725
1798
  serverResponseCode: err.serverResponseCode || err.code
1726
1799
  });
1727
1800
  this.state = 'connectError';
package/lib/schemas.js CHANGED
@@ -170,13 +170,15 @@ const settingsSchema = {
170
170
  .meta({ swaggerHidden: true }),
171
171
 
172
172
  openAiAPIKey: Joi.string().allow('').example('sk-…').description('Your OpenAI API key for AI features').label('OpenAiAPIKey'),
173
- openAiModel: Joi.string().allow('').example('gpt-3.5-turbo').description('OpenAI model to use for text generation').label('OpenAiModel'),
173
+ openAiModel: Joi.string().allow('').example('gpt-5-mini').description('OpenAI model to use for text generation').label('OpenAiModel'),
174
174
 
175
175
  openAiAPIUrl: Joi.string()
176
176
  .uri({ scheme: ['http', 'https'], allowRelative: false })
177
177
  .allow('')
178
178
  .example('https://api.openai.com')
179
- .description('Base URL for OpenAI API (change for OpenAI-compatible services)')
179
+ .description(
180
+ 'Base URL for the OpenAI API. Set for OpenAI-compatible services, including any URL path the service mounts the API under - for Azure OpenAI, use https://<your-resource>.openai.azure.com/openai/v1'
181
+ )
180
182
  .label('OpenAiAPIUrl'),
181
183
 
182
184
  documentStoreChatModel: Joi.string()
@@ -677,6 +679,13 @@ const imapSchema = {
677
679
  .unknown()
678
680
  .description('Advanced TLS configuration options')
679
681
  .label('ImapTlsOptions'),
682
+ // the field name deliberately matches the ImapFlow option name - the stored
683
+ // imap object is merged verbatim into the ImapFlow connection config
684
+ disableIMAP4rev2: Joi.boolean()
685
+ .example(false)
686
+ .description(
687
+ 'Do not use IMAP4rev2 even if the server supports it. Set this for servers with a broken IMAP4rev2 implementation. Only applies to accounts using regular password authentication.'
688
+ ),
680
689
  resyncDelay: Joi.number().integer().example(RESYNC_DELAY).description('Delay in seconds between full mailbox resynchronizations').default(RESYNC_DELAY),
681
690
  disabled: Joi.boolean().example(false).description('Temporarily disable IMAP operations for this account'),
682
691
 
@@ -864,6 +873,11 @@ const imapUpdateSchema = {
864
873
  .unknown()
865
874
  .description('Advanced TLS configuration options')
866
875
  .label('ImapUpdateTlsOptions'),
876
+ disableIMAP4rev2: Joi.boolean()
877
+ .example(false)
878
+ .description(
879
+ 'Do not use IMAP4rev2 even if the server supports it. Set this for servers with a broken IMAP4rev2 implementation. Only applies to accounts using regular password authentication.'
880
+ ),
867
881
  resyncDelay: Joi.number().integer().example(RESYNC_DELAY).description('Delay in seconds between full mailbox resynchronizations'),
868
882
 
869
883
  disabled: Joi.boolean().example(false).description('Temporarily disable IMAP operations for this account'),
package/lib/settings.js CHANGED
@@ -29,6 +29,19 @@ const ENCRYPTED_KEYS = [
29
29
  module.exports = {
30
30
  encryptedKeys: ENCRYPTED_KEYS,
31
31
 
32
+ /**
33
+ * Whether admin authentication is configured for this instance.
34
+ *
35
+ * The single spelling of the test that gates `server.auth.default('session')` in workers/api.js.
36
+ * Routes that are only protected by that default are reachable by anyone when it returns false,
37
+ * so anything they expose has to gate on this explicitly.
38
+ *
39
+ * @returns {Promise<Boolean>} True when an admin password has been set
40
+ */
41
+ async isInstanceSecured() {
42
+ return !!(await module.exports.get('authData'));
43
+ },
44
+
32
45
  async getValue(encryptSecret, key, value) {
33
46
  if (!value) {
34
47
  return null;
package/lib/tokens.js CHANGED
@@ -80,6 +80,21 @@ module.exports = {
80
80
  return true;
81
81
  },
82
82
 
83
+ /**
84
+ * Provisions a new access token.
85
+ *
86
+ * Deliberately unguarded. The admin-password requirement belongs to the routes, not here,
87
+ * because only they can tell whether the caller actually presented a credential. Gating this
88
+ * function instead refused headless deployments too (EENGINE_PREPARED_TOKEN with no admin
89
+ * password is a supported configuration), and the CLI needs shell access anyway.
90
+ *
91
+ * Both HTTP callers gate themselves: POST /admin/tokens/new unconditionally, since
92
+ * `server.auth.default('session')` leaves it open while authData is unset; POST /v1/token only
93
+ * for the `preauth` caller that the `disableTokens` setting lets through without a credential.
94
+ *
95
+ * @param {Object} opts - Token options. May originate from a request payload.
96
+ * @returns {String} The token value (only ever returned here - it is stored hashed)
97
+ */
83
98
  async provision(opts) {
84
99
  opts = opts || {};
85
100
  const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog } = opts;
@@ -1695,7 +1695,9 @@ function init(args) {
1695
1695
  const values = Object.assign({}, flattenObjectKeys(accountData), {
1696
1696
  imap: true,
1697
1697
  imap_disabled: (!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled),
1698
+ imap_tls_ignoreCertErrors: !!(accountData.imap && accountData.imap.tls && accountData.imap.tls.rejectUnauthorized === false),
1698
1699
  smtp: !!accountData.smtp,
1700
+ smtp_tls_ignoreCertErrors: !!(accountData.smtp && accountData.smtp.tls && accountData.smtp.tls.rejectUnauthorized === false),
1699
1701
  oauth2: !!accountData.oauth2,
1700
1702
 
1701
1703
  imap_auth_pass: '',
@@ -1790,9 +1792,7 @@ function init(args) {
1790
1792
  if (request.payload.imap) {
1791
1793
  let imapTls = (oldData.imap && oldData.imap.tls) || {};
1792
1794
 
1793
- let updateKeys = {
1794
- tls: imapTls
1795
- };
1795
+ let updateKeys = {};
1796
1796
 
1797
1797
  for (let key of ['host', 'port', 'disabled', 'sentMailPath']) {
1798
1798
  if (`imap_${key}` in request.payload) {
@@ -1807,6 +1807,22 @@ function init(args) {
1807
1807
  }
1808
1808
  updateKeys.auth = imapAuth;
1809
1809
  updateKeys.secure = request.payload.imap_secure;
1810
+ // The connection settings section is hidden for OAuth2 and disabled
1811
+ // accounts, so like `secure` these only apply when it was submitted.
1812
+ // Written only when the effective state changes - an untouched form
1813
+ // save must not add new keys, as any imap diff forces a reconnect
1814
+ if (request.payload.imap_tls_ignoreCertErrors !== (imapTls.rejectUnauthorized === false)) {
1815
+ imapTls.rejectUnauthorized = !request.payload.imap_tls_ignoreCertErrors;
1816
+ }
1817
+ if (request.payload.imap_disableIMAP4rev2 !== !!(oldData.imap && oldData.imap.disableIMAP4rev2)) {
1818
+ updateKeys.disableIMAP4rev2 = request.payload.imap_disableIMAP4rev2;
1819
+ }
1820
+ }
1821
+
1822
+ // skipped while empty and absent from the stored account for the same
1823
+ // reason as above - a no-op save must not introduce a tls:{} key
1824
+ if (Object.keys(imapTls).length) {
1825
+ updateKeys.tls = imapTls;
1810
1826
  }
1811
1827
 
1812
1828
  updates.imap = Object.assign(oldData.imap || {}, updateKeys);
@@ -1824,13 +1840,23 @@ function init(args) {
1824
1840
  smtpAuth.pass = request.payload.smtp_auth_pass;
1825
1841
  }
1826
1842
 
1843
+ // written only when the effective state changes, and the tls object is
1844
+ // skipped while empty - same as the IMAP flags, a no-op save must not
1845
+ // modify the stored account
1846
+ if (request.payload.smtp_tls_ignoreCertErrors !== (smtpTls.rejectUnauthorized === false)) {
1847
+ smtpTls.rejectUnauthorized = !request.payload.smtp_tls_ignoreCertErrors;
1848
+ }
1849
+
1827
1850
  updates.smtp = Object.assign(oldData.smtp || {}, {
1828
1851
  host: request.payload.smtp_host,
1829
1852
  port: request.payload.smtp_port,
1830
1853
  secure: request.payload.smtp_secure,
1831
- auth: smtpAuth,
1832
- tls: smtpTls
1854
+ auth: smtpAuth
1833
1855
  });
1856
+
1857
+ if (Object.keys(smtpTls).length) {
1858
+ updates.smtp.tls = smtpTls;
1859
+ }
1834
1860
  }
1835
1861
 
1836
1862
  await accountObject.update(updates);
@@ -1852,6 +1878,14 @@ function init(args) {
1852
1878
 
1853
1879
  menuAccounts: true,
1854
1880
  account: request.params.account,
1881
+ // re-render the form from the submitted payload (the field names
1882
+ // match the template values); without this the form comes back
1883
+ // blank and the IMAP/SMTP cards disappear entirely
1884
+ values: Object.assign({}, request.payload, {
1885
+ oauth2: !!accountData.oauth2,
1886
+ imap_auth_pass: '',
1887
+ smtp_auth_pass: ''
1888
+ }),
1855
1889
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
1856
1890
 
1857
1891
  isApi: accountData.isApi,
@@ -1902,6 +1936,14 @@ function init(args) {
1902
1936
  menuAccounts: true,
1903
1937
  account: request.params.account,
1904
1938
  errors,
1939
+ // re-render the form from the (raw, unvalidated) submitted
1940
+ // payload so the entered values and the IMAP/SMTP cards
1941
+ // survive a validation failure
1942
+ values: Object.assign({}, request.payload, {
1943
+ oauth2: !!accountData.oauth2,
1944
+ imap_auth_pass: '',
1945
+ smtp_auth_pass: ''
1946
+ }),
1905
1947
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
1906
1948
 
1907
1949
  isApi: accountData.isApi,
@@ -1945,6 +1987,18 @@ function init(args) {
1945
1987
  .default(false)
1946
1988
  .example(true)
1947
1989
  .description('Should connection use TLS. Usually true for port 993'),
1990
+ imap_tls_ignoreCertErrors: Joi.boolean()
1991
+ .truthy('Y', 'true', '1', 'on')
1992
+ .falsy('N', 'false', 0, '')
1993
+ .default(false)
1994
+ .example(false)
1995
+ .description('Allow connections to servers with invalid TLS certificates for this account'),
1996
+ imap_disableIMAP4rev2: Joi.boolean()
1997
+ .truthy('Y', 'true', '1', 'on')
1998
+ .falsy('N', 'false', 0, '')
1999
+ .default(false)
2000
+ .example(false)
2001
+ .description('Do not use IMAP4rev2 even if the server supports it'),
1948
2002
  imap_disabled: Joi.boolean()
1949
2003
  .truthy('Y', 'true', '1', 'on')
1950
2004
  .falsy('N', 'false', 0, '')
@@ -1988,6 +2042,12 @@ function init(args) {
1988
2042
  .default(false)
1989
2043
  .example(true)
1990
2044
  .description('Should connection use TLS. Usually true for port 465'),
2045
+ smtp_tls_ignoreCertErrors: Joi.boolean()
2046
+ .truthy('Y', 'true', '1', 'on')
2047
+ .falsy('N', 'false', 0, '')
2048
+ .default(false)
2049
+ .example(false)
2050
+ .description('Allow connections to servers with invalid TLS certificates for this account'),
1991
2051
 
1992
2052
  customHeaders: Joi.string()
1993
2053
  .allow('')
@@ -2336,6 +2336,19 @@ return payload;`)
2336
2336
 
2337
2337
  async handler(request) {
2338
2338
  try {
2339
+ // Nothing invalidates an access token once it is minted, so a token handed out while
2340
+ // this route is reachable without a login keeps working afterwards. The route is only
2341
+ // protected by `server.auth.default('session')`, which workers/api.js applies
2342
+ // conditionally - and only in the API worker that observes the password being set, so
2343
+ // it is NOT reliably in force just because a password now exists in Redis (the CLI
2344
+ // `emailengine password` path and sibling API workers never apply it until restart).
2345
+ // So gate on whether THIS request actually carries an authenticated admin session
2346
+ // rather than on the global secured-state: an unauthenticated caller must not mint a
2347
+ // lasting token, and an authenticated admin always may.
2348
+ if (!request.auth.isAuthenticated) {
2349
+ throw Boom.forbidden('Can not provision an access token without an authenticated admin session');
2350
+ }
2351
+
2339
2352
  let data = {
2340
2353
  ip: request.app.ip,
2341
2354
  remoteAddress: request.app.ip,
@@ -13,6 +13,26 @@ const { redis } = require('../db');
13
13
  const { DEFAULT_PAGE_SIZE } = require('../consts');
14
14
  const { formatAccountData } = require('./route-helpers');
15
15
 
16
+ // Worker kinds in the order they are shown on the internals page (known kinds first; any
17
+ // unrecognized kind is appended so nothing is dropped).
18
+ const THREAD_TYPE_ORDER = ['main', 'api', 'imap', 'webhooks', 'submit', 'export', 'smtp', 'imapProxy', 'documents'];
19
+
20
+ // Severity ranking for the per-group health roll-up (higher wins).
21
+ const STATUS_RANK = { success: 0, neutral: 1, warning: 2, error: 3 };
22
+
23
+ // Short description of what each worker kind does, shown on the group card header.
24
+ const THREAD_PURPOSE = {
25
+ main: 'Orchestrates everything else: spawns and monitors the other worker threads, assigns email accounts to the sync workers, routes inter-thread calls, and manages the Redis connection and licensing.',
26
+ api: 'Serves the REST API and the admin web interface (including this page), the OpenAPI documentation, and real-time account updates.',
27
+ imap: 'Keeps email accounts in sync - IMAP, Gmail API and Outlook/Graph - maintaining connections, detecting new and changed messages in real time, and running message and mailbox operations.',
28
+ webhooks: 'Delivers webhook notifications for email and account events over HTTP, with automatic retries and optional per-route filtering and transforms.',
29
+ submit: 'Sends queued outbound email through SMTP or a provider API (Gmail, Outlook), with retries and delivery, bounce and complaint tracking.',
30
+ export: 'Runs bulk account export jobs, extracting matching messages into compressed files for download.',
31
+ documents: 'Indexes emails into the Document Store (ElasticSearch) for search and processing. This is a deprecated feature.',
32
+ smtp: 'Accepts SMTP submissions from legacy applications and queues them for delivery through the associated account.',
33
+ imapProxy: 'Lets standard IMAP clients reach EmailEngine-managed accounts, hiding the OAuth2 complexity of providers like Gmail and Microsoft 365.'
34
+ };
35
+
16
36
  function init(args) {
17
37
  const { server, call } = args;
18
38
 
@@ -47,6 +67,120 @@ function init(args) {
47
67
  bytesFormatter = new Intl.NumberFormat('en-US', bytesFormatterOpts);
48
68
  }
49
69
 
70
+ // Process each thread into row data. The per-thread config (expected worker
71
+ // count) is intentionally NOT surfaced per row here - it is a pool-level fact
72
+ // and is shown once on the group header below.
73
+ let processedThreads = threads.map(threadInfo => {
74
+ // Unresponsive / errored worker: the resource-usage probe failed or timed out.
75
+ if (threadInfo.resourceUsageError) {
76
+ threadInfo.isUnresponsive = true;
77
+ threadInfo.errorMessage = threadInfo.resourceUsageError.error;
78
+ }
79
+
80
+ // CPU metrics removed to prevent potential native code issues
81
+
82
+ // Single health signal (variant + label) used by both the per-row status dot
83
+ // and the per-group roll-up badge.
84
+ threadInfo.statusVariant = 'success';
85
+ threadInfo.statusLabel = 'Healthy';
86
+ if (threadInfo.isUnresponsive) {
87
+ threadInfo.statusVariant = 'error';
88
+ threadInfo.statusLabel = 'Unresponsive';
89
+ } else {
90
+ switch (threadInfo.healthStatus) {
91
+ case 'critical':
92
+ case 'restarting':
93
+ threadInfo.statusVariant = 'error';
94
+ threadInfo.statusLabel = 'Critical';
95
+ break;
96
+ case 'unhealthy':
97
+ threadInfo.statusVariant = 'warning';
98
+ threadInfo.statusLabel = 'Unhealthy';
99
+ break;
100
+ case 'unknown':
101
+ threadInfo.statusVariant = 'neutral';
102
+ threadInfo.statusLabel = 'Unknown';
103
+ break;
104
+ // 'healthy' or undefined -> success / Healthy
105
+ }
106
+ }
107
+
108
+ if (threadInfo.online) {
109
+ threadInfo.timeStr = new Date(threadInfo.online).toISOString();
110
+ }
111
+
112
+ // Format the heap reading for responsive threads. Unresponsive ones have no
113
+ // reading, so the Memory cell shows a dash and the Status column carries the
114
+ // state (heapTotal/rss/external are available but deliberately not displayed).
115
+ if (!threadInfo.isUnresponsive && typeof threadInfo.heapUsed === 'number') {
116
+ threadInfo.heapUsed = bytesFormatter.format(threadInfo.heapUsed).replace(/BB$/, 'GB');
117
+ }
118
+
119
+ // Email (sync) workers own account assignment, but the count field is absent
120
+ // when a worker currently syncs none - show an explicit 0 instead of a blank.
121
+ if (threadInfo.type === 'imap' && typeof threadInfo.accounts !== 'number') {
122
+ threadInfo.accounts = 0;
123
+ }
124
+
125
+ return threadInfo;
126
+ });
127
+
128
+ // Group threads by worker kind so the pool-level facts (expected vs actual count,
129
+ // config env var, health roll-up) live on the group header instead of being
130
+ // repeated on every member row.
131
+ let groupMap = new Map();
132
+ for (let threadInfo of processedThreads) {
133
+ if (!groupMap.has(threadInfo.type)) {
134
+ groupMap.set(threadInfo.type, []);
135
+ }
136
+ groupMap.get(threadInfo.type).push(threadInfo);
137
+ }
138
+
139
+ let orderedTypes = THREAD_TYPE_ORDER.filter(type => groupMap.has(type)).concat(
140
+ [...groupMap.keys()].filter(type => !THREAD_TYPE_ORDER.includes(type))
141
+ );
142
+
143
+ let groups = orderedTypes.map(type => {
144
+ let list = groupMap.get(type);
145
+ let cfg = list[0].config; // { key, value } expected-count config, or undefined
146
+ let expected = cfg && cfg.value != null ? Number(cfg.value) : null;
147
+ let hasExpected = expected !== null && !isNaN(expected);
148
+ let actual = list.length;
149
+
150
+ // Fleet completeness: green when the running count matches the configured
151
+ // count, red when a worker is missing (crashed and not restarted), amber when
152
+ // there are more running than configured.
153
+ let countVariant = 'neutral';
154
+ if (hasExpected) {
155
+ countVariant = actual < expected ? 'error' : actual > expected ? 'warning' : 'success';
156
+ }
157
+
158
+ // Health roll-up = worst member status.
159
+ let rollup = list.reduce(
160
+ (worst, threadInfo) =>
161
+ STATUS_RANK[threadInfo.statusVariant] > STATUS_RANK[worst.variant]
162
+ ? { variant: threadInfo.statusVariant, label: threadInfo.statusLabel }
163
+ : worst,
164
+ { variant: 'success', label: 'Healthy' }
165
+ );
166
+
167
+ return {
168
+ type,
169
+ description: list[0].description || type,
170
+ purpose: THREAD_PURPOSE[type] || null,
171
+ threads: list,
172
+ // Only the sync (email) workers are assigned accounts, so the Accounts
173
+ // column is shown only for that pool.
174
+ showAccounts: type === 'imap',
175
+ hasExpected,
176
+ countLabel: hasExpected ? `${actual} / ${expected} running` : `${actual} running`,
177
+ countVariant,
178
+ configRef: hasExpected ? `${cfg.key}=${expected}` : null,
179
+ healthVariant: rollup.variant,
180
+ healthLabel: rollup.label
181
+ };
182
+ });
183
+
50
184
  return h.view(
51
185
  'internals/index',
52
186
  {
@@ -57,73 +191,7 @@ function init(args) {
57
191
 
58
192
  apiWorkerWarning: apiWorkerScaling && apiWorkerScaling.fallback ? apiWorkerScaling : false,
59
193
 
60
- threads: threads.map(threadInfo => {
61
- // Check if this worker is unresponsive
62
- if (threadInfo.resourceUsageError) {
63
- threadInfo.isUnresponsive = true;
64
- threadInfo.heapUsed = threadInfo.resourceUsageError.unresponsive ? 'UNRESPONSIVE' : 'ERROR';
65
- threadInfo.errorMessage = threadInfo.resourceUsageError.error;
66
- }
67
-
68
- // CPU metrics removed to prevent potential native code issues
69
-
70
- // Process health status
71
- if (threadInfo.healthStatus) {
72
- switch (threadInfo.healthStatus) {
73
- case 'unhealthy':
74
- threadInfo.healthBadge = 'Unhealthy';
75
- threadInfo.healthBadgeType = 'warning';
76
- break;
77
- case 'critical':
78
- case 'restarting':
79
- threadInfo.healthBadge = 'Critical';
80
- threadInfo.healthBadgeType = 'error';
81
- break;
82
- case 'unknown':
83
- threadInfo.healthBadge = 'Unknown';
84
- threadInfo.healthBadgeType = 'neutral';
85
- break;
86
- // healthy - no badge shown to avoid clutter
87
- }
88
- }
89
-
90
- for (let key of Object.keys(threadInfo)) {
91
- switch (key) {
92
- case 'online':
93
- threadInfo.timeStr = new Date(threadInfo.online).toISOString();
94
- break;
95
-
96
- /*
97
- // managed by the template helper
98
- case 'messages':
99
- case 'called':
100
- case 'accounts':
101
- case 'threadId':
102
- threadInfo[key] = threadInfo[key];
103
- break;
104
- */
105
-
106
- case 'heapUsed':
107
- if (!threadInfo.isUnresponsive) {
108
- threadInfo.heapUsed = bytesFormatter.format(threadInfo[key]).replace(/BB$/, 'GB');
109
- }
110
- break;
111
-
112
- case 'heapTotal':
113
- // Not displayed anymore to avoid confusion with heap limit
114
- break;
115
-
116
- // Handle other memory metrics from new format
117
- case 'rss':
118
- case 'external':
119
- case 'arrayBuffers':
120
- // These are available but not displayed in the current UI
121
- break;
122
- }
123
- }
124
-
125
- return threadInfo;
126
- })
194
+ groups
127
195
  },
128
196
  {
129
197
  layout: 'app'