emailengine-app 2.81.2 → 2.82.0

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.
Files changed (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
package/static/js/ui.js CHANGED
@@ -976,59 +976,47 @@ document.addEventListener('DOMContentLoaded', () => {
976
976
  }
977
977
  });
978
978
 
979
- // The account picker (views/partials/ui/account-picker.hbs).
979
+ // The pickers (views/partials/ui/picker.hbs): one control with two faces, a search box with
980
+ // suggestions and a card naming what was picked, over whatever a page needs chosen from. Two
981
+ // sources exist. The account picker asks the server as the person types, because the account
982
+ // set is unbounded and every row costs a listing; the model picker filters a list the page
983
+ // already holds, because a provider serves a hundred models at most.
980
984
  //
981
- // A free-text account id is a field only the person who already knows the id can fill in, so the
982
- // control is a search box: type any part of an id, a name or an address, pick from the
983
- // suggestions, and the box is replaced by a card naming what was picked.
985
+ // The posted value never stops being a plain id in the hidden input the partial renders, and
986
+ // every change to it fires `input` and `change` there - so a page that watches that field (the
987
+ // MCP tool count follows the account on all three pages that mint a token) needs no knowledge of
988
+ // this at all. Everything below is about which id is in that input, and nothing else reads it.
984
989
  //
985
- // The posted value never stops being a plain account id in the hidden input the partial renders,
986
- // and every change to it fires `input` and `change` there - so a page that watches that field (the
987
- // MCP tool count follows it on all three pages that mint a token) needs no knowledge of this at
988
- // all. Everything below is about which id is in that input, and nothing else reads the choice.
989
- const uiAccountPickerEndpoint = '/admin/accounts/suggestions';
990
-
991
- // How long a keystroke waits before it becomes a request. Long enough that typing an account id
992
- // costs one round trip rather than twenty, short enough to feel like the list is following along.
993
- const uiAccountPickerDebounce = 200;
994
-
995
990
  // Every row is built as DOM nodes with textContent - account names and addresses are attacker-set
996
- // (a display name arrives from a provider), and this list is rendered on an authenticated admin
997
- // page, which is the worst place to hand one an innerHTML.
998
- const uiAccountPickerLine = (className, text) => {
991
+ // (a display name arrives from a provider), model names and notes arrive from an API, and these
992
+ // rows are rendered on an authenticated admin page, which is the worst place to hand one an
993
+ // innerHTML. The ee-account-picker-* classes are the one set of styles both pickers share.
994
+ const uiPickerLine = (className, text) => {
999
995
  const elm = document.createElement('div');
1000
996
  elm.className = className;
1001
997
  elm.textContent = text;
1002
998
  return elm;
1003
999
  };
1004
1000
 
1005
- // The name a person recognises. An account may carry none, in which case the address is the name,
1006
- // and an account with neither is only ever its id.
1007
- const uiAccountPickerTitle = entry => entry.name || entry.email || entry.account;
1008
-
1009
- const uiAccountPickerBadge = entry => {
1010
- if (!entry.state || !entry.state.name) {
1011
- return null;
1012
- }
1001
+ const uiPickerBadge = (text, className) => {
1013
1002
  const badge = document.createElement('span');
1014
- badge.className = 'badge badge-sm badge-' + (entry.state.type || 'neutral');
1015
- badge.textContent = entry.state.name;
1003
+ badge.className = 'badge badge-sm ' + className;
1004
+ badge.textContent = text;
1016
1005
  return badge;
1017
1006
  };
1018
1007
 
1019
- // The title line: the name a person recognises, plus the connection state. Shared by the card and
1020
- // by a result row, which differ only in the weight of the name - the two faces of the control are
1021
- // meant to read as the same thing, and building them from one place is what keeps them that way.
1022
- const uiAccountPickerTitleLine = (entry, nameClass) => {
1008
+ // The title line: the name a person recognises, plus a badge. Shared by the card and by a result
1009
+ // row, which differ only in the weight of the name - the two faces of the control are meant to
1010
+ // read as the same thing, and building them from one place is what keeps them that way.
1011
+ const uiPickerTitleLine = (name, badge, nameClass) => {
1023
1012
  const title = document.createElement('div');
1024
1013
  title.className = 'flex items-center gap-2 min-w-0';
1025
1014
 
1026
- const name = document.createElement('span');
1027
- name.className = nameClass;
1028
- name.textContent = uiAccountPickerTitle(entry);
1029
- title.append(name);
1015
+ const elm = document.createElement('span');
1016
+ elm.className = nameClass;
1017
+ elm.textContent = name;
1018
+ title.append(elm);
1030
1019
 
1031
- const badge = uiAccountPickerBadge(entry);
1032
1020
  if (badge) {
1033
1021
  title.append(badge);
1034
1022
  }
@@ -1036,47 +1024,64 @@ const uiAccountPickerTitleLine = (entry, nameClass) => {
1036
1024
  return title;
1037
1025
  };
1038
1026
 
1039
- // The identifying line under the title: the address when it is not already the title, and the id,
1040
- // which is the value actually being chosen and so is always shown. One line rather than two, so a
1041
- // screenful of the dropdown is a useful number of accounts to choose between.
1042
- const uiAccountPickerDetails = entry => {
1043
- const line = uiAccountPickerLine('text-base-content/60 truncate text-xs', '');
1044
- line.title = entry.account;
1027
+ // The identifying line under the title: a note or an address when there is one, and the id,
1028
+ // which is the value actually being chosen and so is always shown. One line rather than two, so
1029
+ // a screenful of the dropdown is a useful number of rows to choose between.
1030
+ const uiPickerDetails = (note, id) => {
1031
+ const line = uiPickerLine('text-base-content/60 truncate text-xs', '');
1032
+ line.title = id;
1045
1033
 
1046
- if (entry.email && entry.email !== uiAccountPickerTitle(entry)) {
1047
- line.append(entry.email + ' \u00b7 ');
1034
+ if (note) {
1035
+ line.append(note + (id ? ' · ' : ''));
1048
1036
  }
1049
1037
 
1050
- const id = document.createElement('span');
1051
- id.className = 'font-mono';
1052
- id.textContent = entry.account;
1053
- line.append(id);
1038
+ if (id) {
1039
+ const elm = document.createElement('span');
1040
+ elm.className = 'font-mono';
1041
+ elm.textContent = id;
1042
+ line.append(elm);
1043
+ }
1054
1044
 
1055
1045
  return line;
1056
1046
  };
1057
1047
 
1058
- window.uiAccountPicker = root => {
1048
+ /**
1049
+ * Wires one picker. The adapter says what an entry is and where entries come from:
1050
+ * value(entry) the id the hidden input carries
1051
+ * title(entry, nameClass) the title line element
1052
+ * details(entry) the line under it
1053
+ * load(query, trigger) a promise of rows for a query: [{ note }] for a heading or a remark,
1054
+ * [{ entry }] for a choice; trigger is 'input' or 'focus'
1055
+ * cancel() called when the search is left, to stop a request in flight (optional)
1056
+ * resolve(value) the entry for a stored value, when the adapter can tell (optional)
1057
+ * cardAction 'clear': the card's button empties the value; 'change': it reopens
1058
+ * the search with the value kept until a new choice is made
1059
+ * cardLabel, cardIcon the button's accessible label and icon class
1060
+ * failed the remark shown when load() rejects
1061
+ *
1062
+ * @param {Element} root - the [data-picker] element
1063
+ * @param {Object} adapter
1064
+ */
1065
+ window.uiPicker = (root, adapter) => {
1059
1066
  const input = document.getElementById(root.dataset.input);
1060
1067
  const card = root.querySelector('[data-picker-card]');
1061
1068
  const search = root.querySelector('[data-picker-search]');
1062
1069
  const results = root.querySelector('[data-picker-results]');
1063
- const box = search.querySelector('input');
1070
+ const box = search && search.querySelector('input');
1064
1071
 
1065
1072
  if (!input || !card || !results || !box) {
1066
1073
  return;
1067
1074
  }
1068
1075
 
1069
- let entries = [];
1070
- // The rendered option nodes, so moving the highlight touches two of them rather than
1071
- // re-querying the list and rewriting every row
1076
+ // The rendered option nodes and the entries behind them, in order, so moving the highlight
1077
+ // touches two nodes rather than re-querying the list and rewriting every row
1072
1078
  let options = [];
1079
+ let entries = [];
1073
1080
  let active = -1;
1074
- let timer = null;
1075
- let inflight = null;
1076
- // The last answered query and its result. A refocus on unchanged text repaints from this
1077
- // instead of asking the server for the same page again - every one of those costs an account
1078
- // listing, and tabbing through a form would otherwise pay for one per pass.
1079
- let cached = null;
1081
+ // The entry the card shows, so leaving the search without a choice puts it back
1082
+ let current = null;
1083
+ // The load whose answer is still wanted; an older one that lands later is dropped
1084
+ let generation = 0;
1080
1085
 
1081
1086
  const open = () => {
1082
1087
  results.classList.remove('hidden');
@@ -1088,14 +1093,15 @@ window.uiAccountPicker = root => {
1088
1093
  results.replaceChildren();
1089
1094
  box.setAttribute('aria-expanded', 'false');
1090
1095
  box.removeAttribute('aria-activedescendant');
1091
- entries = [];
1092
1096
  options = [];
1097
+ entries = [];
1093
1098
  active = -1;
1094
1099
  };
1095
1100
 
1096
1101
  // Paints whichever of the two faces the control currently has. Called for every change of the
1097
1102
  // selection, so the card and the search box can never both be showing.
1098
1103
  const paint = selected => {
1104
+ current = selected;
1099
1105
  card.replaceChildren();
1100
1106
 
1101
1107
  if (!selected) {
@@ -1106,22 +1112,32 @@ window.uiAccountPicker = root => {
1106
1112
 
1107
1113
  const text = document.createElement('div');
1108
1114
  text.className = 'min-w-0 grow';
1109
- text.append(uiAccountPickerTitleLine(selected, 'font-medium truncate'), uiAccountPickerDetails(selected));
1110
-
1111
- const clear = document.createElement('button');
1112
- clear.type = 'button';
1113
- clear.className = 'btn btn-text btn-sm btn-circle shrink-0';
1114
- clear.setAttribute('aria-label', 'Clear the selected account');
1115
- const clearIcon = document.createElement('span');
1116
- clearIcon.className = 'icon-[tabler--x] size-4';
1117
- clear.append(clearIcon);
1118
- clear.addEventListener('click', () => clearSelection(true));
1119
-
1120
- card.append(text, clear);
1115
+ text.append(adapter.title(selected, 'font-medium truncate'), adapter.details(selected));
1116
+
1117
+ const button = document.createElement('button');
1118
+ button.type = 'button';
1119
+ button.className = 'btn btn-text btn-sm btn-circle shrink-0';
1120
+ button.setAttribute('aria-label', adapter.cardLabel);
1121
+ const icon = document.createElement('span');
1122
+ icon.className = adapter.cardIcon + ' size-4';
1123
+ button.append(icon);
1124
+ button.addEventListener('click', () => (adapter.cardAction === 'clear' ? clearSelection(true) : change()));
1125
+
1126
+ card.append(text, button);
1121
1127
  card.classList.remove('hidden');
1122
1128
  search.classList.add('hidden');
1123
1129
  };
1124
1130
 
1131
+ // The one writer of the hidden input. The events are what the rest of the page listens to, and
1132
+ // a programmatic value assignment fires neither on its own.
1133
+ const select = selected => {
1134
+ close();
1135
+ input.value = selected ? adapter.value(selected) : '';
1136
+ paint(selected);
1137
+ input.dispatchEvent(new Event('input', { bubbles: true }));
1138
+ input.dispatchEvent(new Event('change', { bubbles: true }));
1139
+ };
1140
+
1125
1141
  // Back to empty: the hidden input, the card and the search box all have to agree, so this is
1126
1142
  // one path rather than a clear button that happens to do the same three things.
1127
1143
  const clearSelection = focus => {
@@ -1132,14 +1148,11 @@ window.uiAccountPicker = root => {
1132
1148
  }
1133
1149
  };
1134
1150
 
1135
- // The one writer of the hidden input. The events are what the rest of the page listens to, and
1136
- // a programmatic value assignment fires neither on its own.
1137
- const select = selected => {
1138
- close();
1139
- input.value = selected ? selected.account : '';
1140
- paint(selected);
1141
- input.dispatchEvent(new Event('input', { bubbles: true }));
1142
- input.dispatchEvent(new Event('change', { bubbles: true }));
1151
+ // Back to the search with the value kept: the card returns if nothing new is chosen
1152
+ const change = () => {
1153
+ paint(null);
1154
+ box.value = '';
1155
+ box.focus();
1143
1156
  };
1144
1157
 
1145
1158
  // Wraps at both ends, so ArrowUp from nothing selected lands on the last row
@@ -1163,93 +1176,60 @@ window.uiAccountPicker = root => {
1163
1176
  option.scrollIntoView({ block: 'nearest' });
1164
1177
  };
1165
1178
 
1166
- const render = data => {
1179
+ const render = rows => {
1167
1180
  results.replaceChildren();
1168
- entries = data.accounts || [];
1169
1181
  options = [];
1182
+ entries = [];
1170
1183
  active = -1;
1171
1184
 
1172
- if (!entries.length) {
1173
- results.append(uiAccountPickerLine('ee-account-picker-note', 'No account matches that.'));
1174
- }
1185
+ for (const row of rows) {
1186
+ if (!row.entry) {
1187
+ results.append(uiPickerLine('ee-account-picker-note', row.note));
1188
+ continue;
1189
+ }
1175
1190
 
1176
- entries.forEach((entry, index) => {
1191
+ const index = options.length;
1177
1192
  const option = document.createElement('button');
1178
1193
  option.type = 'button';
1179
1194
  option.id = box.id + '-option-' + index;
1180
1195
  option.className = 'ee-account-picker-option';
1181
1196
  option.setAttribute('role', 'option');
1182
1197
  option.setAttribute('aria-selected', 'false');
1183
- option.append(uiAccountPickerTitleLine(entry, 'truncate'), uiAccountPickerDetails(entry));
1198
+ option.append(adapter.title(row.entry, 'truncate'), adapter.details(row.entry));
1184
1199
 
1185
1200
  // mousedown rather than click: the box loses focus first otherwise, and the blur
1186
1201
  // handler closes the list out from under the click that was choosing from it
1187
1202
  option.addEventListener('mousedown', event => {
1188
1203
  event.preventDefault();
1189
- select(entry);
1204
+ select(row.entry);
1190
1205
  });
1191
1206
  option.addEventListener('mouseenter', () => highlight(index));
1192
1207
 
1193
1208
  options.push(option);
1209
+ entries.push(row.entry);
1194
1210
  results.append(option);
1195
- });
1196
-
1197
- // Said out loud rather than left as a list that silently stops: the reader would otherwise
1198
- // read a capped list as the whole instance
1199
- if (data.more > 0) {
1200
- results.append(uiAccountPickerLine('ee-account-picker-note', data.more + ' more match. Type a little more to narrow it down.'));
1201
1211
  }
1202
1212
 
1203
1213
  open();
1204
1214
  };
1205
1215
 
1206
- const load = () => {
1207
- const query = box.value.trim();
1208
-
1209
- if (cached && cached.query === query) {
1210
- render(cached.data);
1211
- return;
1212
- }
1213
-
1214
- // A request the box has already moved on from is cancelled rather than left to finish:
1215
- // each one is a full account listing, and a typed word would otherwise leave several of
1216
- // them running server-side for a result nobody paints.
1217
- if (inflight) {
1218
- inflight.abort();
1219
- }
1220
- const controller = new AbortController();
1221
- inflight = controller;
1222
-
1223
- fetch(uiAccountPickerEndpoint + (query ? '?query=' + encodeURIComponent(query) : ''), {
1224
- headers: { accept: 'application/json' },
1225
- signal: controller.signal
1226
- })
1227
- .then(res => (res.ok ? res.json() : Promise.reject(new Error('HTTP ' + res.status))))
1228
- .then(data => {
1229
- cached = { query, data };
1230
- render(data);
1216
+ const load = trigger => {
1217
+ const mine = ++generation;
1218
+ Promise.resolve(adapter.load(box.value.trim(), trigger))
1219
+ .then(rows => {
1220
+ if (mine === generation) {
1221
+ render(rows);
1222
+ }
1231
1223
  })
1232
- .catch(err => {
1233
- // An aborted request was superseded; its replacement is already on its way
1234
- if (err.name === 'AbortError') {
1235
- return;
1224
+ .catch(() => {
1225
+ if (mine === generation) {
1226
+ render([{ note: adapter.failed }]);
1236
1227
  }
1237
- results.replaceChildren(uiAccountPickerLine('ee-account-picker-note', 'The account list could not be loaded.'));
1238
- options = [];
1239
- active = -1;
1240
- open();
1241
1228
  });
1242
1229
  };
1243
1230
 
1244
- const schedule = () => {
1245
- window.clearTimeout(timer);
1246
- timer = window.setTimeout(load, uiAccountPickerDebounce);
1247
- };
1248
-
1249
- box.addEventListener('input', schedule);
1250
- // Reopening on an unchanged box repaints from the cache, so this is only a request when the
1251
- // text has actually moved on since the list was last filled in
1252
- box.addEventListener('focus', load);
1231
+ box.addEventListener('input', () => load('input'));
1232
+ box.addEventListener('focus', () => load('focus'));
1253
1233
 
1254
1234
  box.addEventListener('keydown', event => {
1255
1235
  switch (event.key) {
@@ -1268,41 +1248,237 @@ window.uiAccountPicker = root => {
1268
1248
  }
1269
1249
  break;
1270
1250
  case 'Escape':
1271
- close();
1251
+ box.blur();
1272
1252
  break;
1273
1253
  }
1274
1254
  });
1275
1255
 
1256
+ // Leaving the search without a choice: nothing in flight is wanted any more, and the card
1257
+ // comes back for a value that still stands
1276
1258
  box.addEventListener('blur', () => {
1277
- window.clearTimeout(timer);
1278
- if (inflight) {
1279
- inflight.abort();
1280
- inflight = null;
1259
+ generation++;
1260
+ if (adapter.cancel) {
1261
+ adapter.cancel();
1281
1262
  }
1282
1263
  close();
1264
+ paint(current);
1283
1265
  });
1284
1266
 
1285
- // Reached from the card's own clear button and, through window.uiAccountPickerClear() below,
1286
- // from a page resetting a form it did not build.
1267
+ // Reached from the card's own button and, through window.uiPickerClear() below, from a page
1268
+ // resetting a form it did not build
1287
1269
  root.uiPickerClear = clearSelection;
1270
+ // For a page that replaced the adapter's list: the card follows the value into the new one
1271
+ root.uiPickerRepaint = () => paint((adapter.resolve && adapter.resolve(input.value)) || null);
1288
1272
 
1289
- // A stored value the server could resolve renders as the account it names; one it could not is
1290
- // still shown, because an id pointing at a deleted account is exactly the thing the person
1291
- // filling in the form needs to see rather than an empty box.
1273
+ // A stored value the server could resolve renders as what it names; one it could not is still
1274
+ // shown, because an id pointing at a deleted account is exactly the thing the person filling
1275
+ // in the form needs to see rather than an empty box
1292
1276
  let initial = null;
1293
1277
  try {
1294
1278
  initial = JSON.parse(root.dataset.selected || 'null');
1295
1279
  } catch (err) {
1296
1280
  initial = null;
1297
1281
  }
1298
- if (!initial && input.value) {
1299
- initial = { account: input.value, name: '', email: '', state: { type: 'error', name: 'No such account' } };
1282
+ paint(initial || (adapter.resolve && adapter.resolve(input.value)) || null);
1283
+ };
1284
+
1285
+ // Accounts come from GET /admin/accounts/suggestions as the person types. A keystroke waits
1286
+ // 200 ms before it becomes a request, long enough that typing an id costs one round trip rather
1287
+ // than twenty, short enough to feel like the list is following along; the last answer is kept,
1288
+ // so a refocus on unchanged text repaints from it instead of paying for another listing
1289
+ const uiAccountPickerAdapter = () => {
1290
+ const endpoint = '/admin/accounts/suggestions';
1291
+ let timer = null;
1292
+ let inflight = null;
1293
+ let cached = null;
1294
+
1295
+ // The name a person recognises. An account may carry none, in which case the address is the
1296
+ // name, and an account with neither is only ever its id
1297
+ const title = entry => entry.name || entry.email || entry.account;
1298
+
1299
+ const badge = entry => (entry.state && entry.state.name ? uiPickerBadge(entry.state.name, 'badge-' + (entry.state.type || 'neutral')) : null);
1300
+
1301
+ const fetchRows = query =>
1302
+ new Promise((resolve, reject) => {
1303
+ if (inflight) {
1304
+ inflight.abort();
1305
+ }
1306
+ const controller = new AbortController();
1307
+ inflight = controller;
1308
+
1309
+ fetch(endpoint + (query ? '?query=' + encodeURIComponent(query) : ''), {
1310
+ headers: { accept: 'application/json' },
1311
+ signal: controller.signal
1312
+ })
1313
+ .then(res => (res.ok ? res.json() : Promise.reject(new Error('HTTP ' + res.status))))
1314
+ .then(data => {
1315
+ const rows = (data.accounts || []).map(entry => ({ entry }));
1316
+ if (!rows.length) {
1317
+ rows.push({ note: 'No account matches that.' });
1318
+ }
1319
+ // Said out loud rather than left as a list that silently stops: the reader
1320
+ // would otherwise read a capped list as the whole instance
1321
+ if (data.more > 0) {
1322
+ rows.push({ note: data.more + ' more match. Type a little more to narrow it down.' });
1323
+ }
1324
+ cached = { query, rows };
1325
+ resolve(rows);
1326
+ })
1327
+ .catch(err => {
1328
+ // an aborted request was superseded; its replacement is already on its way
1329
+ if (err.name !== 'AbortError') {
1330
+ reject(err);
1331
+ }
1332
+ });
1333
+ });
1334
+
1335
+ return {
1336
+ value: entry => entry.account,
1337
+ title: (entry, nameClass) => uiPickerTitleLine(title(entry), badge(entry), nameClass),
1338
+ details: entry => uiPickerDetails(entry.email && entry.email !== title(entry) ? entry.email : '', entry.account),
1339
+ cardAction: 'clear',
1340
+ cardLabel: 'Clear the selected account',
1341
+ cardIcon: 'icon-[tabler--x]',
1342
+ failed: 'The account list could not be loaded.',
1343
+ resolve: value => (value ? { account: value, name: '', email: '', state: { type: 'error', name: 'No such account' } } : null),
1344
+ load: (query, trigger) => {
1345
+ window.clearTimeout(timer);
1346
+ if (cached && cached.query === query) {
1347
+ return cached.rows;
1348
+ }
1349
+ if (trigger !== 'input') {
1350
+ return fetchRows(query);
1351
+ }
1352
+ return new Promise(resolve => {
1353
+ timer = window.setTimeout(() => resolve(fetchRows(query)), 200);
1354
+ });
1355
+ },
1356
+ cancel: () => {
1357
+ window.clearTimeout(timer);
1358
+ if (inflight) {
1359
+ inflight.abort();
1360
+ inflight = null;
1361
+ }
1362
+ }
1363
+ };
1364
+ };
1365
+
1366
+ // The terms of a model's id, name or note, and of what is typed to find it: lower-cased and split
1367
+ // on whitespace and punctuation, so "gpt 6", "gpt-6" and "6 luna" all reach gpt-6-luna
1368
+ const uiPickerTerms = value =>
1369
+ String(value || '')
1370
+ .toLowerCase()
1371
+ .split(/[^\p{L}\p{N}]+/u)
1372
+ .filter(Boolean);
1373
+
1374
+ // A model entry with its terms worked out once, not on every keystroke
1375
+ const uiModelIndexEntry = entry => ({
1376
+ entry,
1377
+ id: uiPickerTerms(entry.id),
1378
+ name: uiPickerTerms(entry.name),
1379
+ description: uiPickerTerms(entry.description),
1380
+ text: [entry.id, entry.name, entry.description].join(' ').toLowerCase()
1381
+ });
1382
+
1383
+ // How well an indexed entry answers a query, 0 when it does not. Every typed term has to open a
1384
+ // term of the entry, and one found in the id outweighs one found in the name, which outweighs one
1385
+ // found in the note. Terms that follow the id's own order score extra, more so from its start
1386
+ // and when they cover all of it, which is what puts gpt-6-luna above gpt-5.6-luna for "gpt 6"
1387
+ // and an exact id above its dated snapshots. The whole query as a substring is the last resort,
1388
+ // for a fragment typed from the middle of a term
1389
+ const uiModelScore = (indexed, query, terms) => {
1390
+ let score = 0;
1391
+ for (const term of terms) {
1392
+ const weight = [
1393
+ [indexed.id, 4],
1394
+ [indexed.name, 2],
1395
+ [indexed.description, 1]
1396
+ ].reduce((best, [field, value]) => (value > best && field.some(token => token.startsWith(term)) ? value : best), 0);
1397
+ if (!weight) {
1398
+ return indexed.text.includes(query) ? 1 : 0;
1399
+ }
1400
+ score += weight;
1401
+ }
1402
+
1403
+ for (let start = 0; start + terms.length <= indexed.id.length; start++) {
1404
+ if (terms.every((term, i) => indexed.id[start + i].startsWith(term))) {
1405
+ score += 3;
1406
+ if (start === 0) {
1407
+ score += 3;
1408
+ }
1409
+ if (terms.length === indexed.id.length) {
1410
+ score += 3;
1411
+ }
1412
+ break;
1413
+ }
1414
+ }
1415
+
1416
+ return score + (indexed.entry.recommended ? 1 : 0);
1417
+ };
1418
+
1419
+ // Models are the list the page holds, handed over through data-models and replaced after a
1420
+ // refresh with window.uiModelPickerSetModels(). With nothing typed, the recommended ones come
1421
+ // first under their own heading, so the sane choice is also the easy one; with something typed,
1422
+ // the best answers come first, scored by uiModelScore()
1423
+ const uiModelPickerAdapter = root => {
1424
+ let models = [];
1425
+ let index = [];
1426
+ const setModels = list => {
1427
+ models = Array.isArray(list) ? list : [];
1428
+ index = models.map(uiModelIndexEntry);
1429
+ };
1430
+ try {
1431
+ setModels(JSON.parse(root.dataset.models || '[]'));
1432
+ } catch (err) {
1433
+ setModels([]);
1300
1434
  }
1301
- paint(initial);
1435
+
1436
+ return {
1437
+ value: entry => entry.id,
1438
+ title: (entry, nameClass) => uiPickerTitleLine(entry.name || entry.id, entry.recommended ? uiPickerBadge('Recommended', 'badge-soft badge-success') : null, nameClass),
1439
+ details: entry => uiPickerDetails(entry.description || '', entry.id),
1440
+ cardAction: 'change',
1441
+ cardLabel: 'Choose another model',
1442
+ cardIcon: 'icon-[tabler--pencil]',
1443
+ failed: 'The model list could not be shown.',
1444
+ // a stored name the list does not carry is shown as it is: a model the key lost access to
1445
+ // is exactly the thing the person filling in the form needs to see
1446
+ resolve: value => models.find(entry => entry.id === value) || (value ? { id: value, name: value, description: 'Not in the list this API key can use' } : null),
1447
+ load: query => {
1448
+ const terms = uiPickerTerms(query);
1449
+ if (terms.length) {
1450
+ const ranked = index
1451
+ .map(indexed => ({ entry: indexed.entry, score: uiModelScore(indexed, query.toLowerCase(), terms) }))
1452
+ .filter(row => row.score > 0)
1453
+ // a stable sort, so equal scores keep the list's own order
1454
+ .sort((a, b) => b.score - a.score);
1455
+ return ranked.length ? ranked.map(({ entry }) => ({ entry })) : [{ note: 'No model matches that.' }];
1456
+ }
1457
+
1458
+ if (!models.length) {
1459
+ return [{ note: 'No model matches that.' }];
1460
+ }
1461
+ const shown = models.filter(entry => entry.recommended).concat(models.filter(entry => !entry.recommended));
1462
+ const rows = [];
1463
+ let heading = null;
1464
+ for (const entry of shown) {
1465
+ const group = entry.recommended ? 'Recommended' : 'Other models';
1466
+ if (group !== heading) {
1467
+ rows.push({ note: group });
1468
+ heading = group;
1469
+ }
1470
+ rows.push({ entry });
1471
+ }
1472
+ return rows;
1473
+ },
1474
+ setModels
1475
+ };
1302
1476
  };
1303
1477
 
1478
+ const uiPickerAdapters = { account: uiAccountPickerAdapter, model: uiModelPickerAdapter };
1479
+
1304
1480
  /**
1305
- * Clears an account picker, given its hidden input.
1481
+ * Clears a picker, given its hidden input.
1306
1482
  *
1307
1483
  * For pages that reset a form as a whole - the template page empties its "send test email" modal
1308
1484
  * every time it opens. Assigning '' to the input is not enough on its own: the card is painted from
@@ -1310,15 +1486,35 @@ window.uiAccountPicker = root => {
1310
1486
  *
1311
1487
  * @param {Element} input - the picker's hidden input
1312
1488
  */
1313
- window.uiAccountPickerClear = input => {
1314
- const root = input && input.closest && input.closest('[data-account-picker]');
1489
+ window.uiPickerClear = input => {
1490
+ const root = input && input.closest && input.closest('[data-picker]');
1315
1491
  if (root && root.uiPickerClear) {
1316
1492
  root.uiPickerClear();
1317
1493
  }
1318
1494
  };
1495
+ window.uiAccountPickerClear = window.uiPickerClear;
1496
+
1497
+ /**
1498
+ * Replaces a model picker's list, given its hidden input. The choice stands, repainted from the
1499
+ * new entries.
1500
+ *
1501
+ * @param {Element} input - the picker's hidden input
1502
+ * @param {Object[]} models - the new entries, "Default" first
1503
+ */
1504
+ window.uiModelPickerSetModels = (input, models) => {
1505
+ const root = input && input.closest && input.closest('[data-picker]');
1506
+ if (root && root.uiPickerAdapter && root.uiPickerAdapter.setModels) {
1507
+ root.uiPickerAdapter.setModels(models);
1508
+ root.uiPickerRepaint();
1509
+ }
1510
+ };
1319
1511
 
1320
1512
  document.addEventListener('DOMContentLoaded', () => {
1321
- for (let root of document.querySelectorAll('[data-account-picker]')) {
1322
- window.uiAccountPicker(root);
1513
+ for (let root of document.querySelectorAll('[data-picker]')) {
1514
+ const adapter = uiPickerAdapters[root.dataset.picker];
1515
+ if (adapter) {
1516
+ root.uiPickerAdapter = adapter(root);
1517
+ window.uiPicker(root, root.uiPickerAdapter);
1518
+ }
1323
1519
  }
1324
1520
  });