@rapidmx/web-client 0.5.0 → 0.7.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 (224) hide show
  1. package/README.md +88 -0
  2. package/apps/shared/components/admin/layout/AdminShell.tsx +25 -8
  3. package/apps/shared/components/admin/settings/BrandingForm.tsx +398 -385
  4. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -112
  5. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +159 -152
  6. package/apps/shared/components/admin/settings/PluginsManager.tsx +1288 -1235
  7. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +9 -1
  8. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -290
  9. package/apps/shared/components/admin/setup/SetupWizard.tsx +443 -416
  10. package/apps/shared/components/calendar/layout/CalendarShell.tsx +194 -192
  11. package/apps/shared/components/contacts/layout/ContactsShell.tsx +199 -197
  12. package/apps/shared/components/layout/AppShell.tsx +288 -270
  13. package/apps/shared/components/mail/ConversationList.tsx +225 -33
  14. package/apps/shared/components/mail/ConversationThreadPane.tsx +434 -216
  15. package/apps/shared/components/mail/MailListToolbar.tsx +265 -0
  16. package/apps/shared/components/mail/MailSelectionBar.tsx +222 -0
  17. package/apps/shared/components/mail/MenuButton.tsx +384 -0
  18. package/apps/shared/components/mail/MessageDetailPane.tsx +280 -215
  19. package/apps/shared/components/mail/MoveToFolderDialog.tsx +263 -0
  20. package/apps/shared/components/mail/compose/ComposeContext.tsx +29 -2
  21. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1700 -1652
  22. package/apps/shared/components/mail/compose/RecipientInput.tsx +356 -0
  23. package/apps/shared/components/mail/compose/RichTextEditor.tsx +38 -3
  24. package/apps/shared/components/mail/compose/quotedBody.ts +100 -0
  25. package/apps/shared/components/mail/compose/recipients.ts +104 -0
  26. package/apps/shared/components/mail/labelMenu.tsx +278 -0
  27. package/apps/shared/components/mail/layout/MailShell.tsx +31 -4
  28. package/apps/shared/components/mail/listPreferences.ts +228 -0
  29. package/apps/shared/components/settings/layout/SettingsShell.tsx +23 -10
  30. package/apps/shared/components/tasks/layout/TasksShell.tsx +201 -199
  31. package/apps/shared/plugins/pluginNav.ts +73 -0
  32. package/apps/shared/search/localIndexRpcClient.ts +3 -1
  33. package/apps/shared/styles/app.css +28 -5
  34. package/apps/www/index.tsx +1854 -1314
  35. package/apps/www/messages/[uid].tsx +5 -4
  36. package/dist/apps/admin/_404.d.ts +2 -0
  37. package/dist/apps/admin/_500.d.ts +2 -0
  38. package/dist/apps/admin/_layout.d.ts +8 -0
  39. package/dist/apps/admin/audit-log/index.d.ts +11 -0
  40. package/dist/apps/admin/branding/index.d.ts +3 -0
  41. package/dist/apps/admin/data-requests/index.d.ts +3 -0
  42. package/dist/apps/admin/distribution-lists/[uid].d.ts +7 -0
  43. package/dist/apps/admin/distribution-lists/index.d.ts +3 -0
  44. package/dist/apps/admin/distribution-lists/new/index.d.ts +3 -0
  45. package/dist/apps/admin/domains/[uid].d.ts +7 -0
  46. package/dist/apps/admin/domains/index.d.ts +3 -0
  47. package/dist/apps/admin/domains/new/index.d.ts +3 -0
  48. package/dist/apps/admin/encryption-policy/index.d.ts +3 -0
  49. package/dist/apps/admin/escrow-scopes/[uid].d.ts +21 -0
  50. package/dist/apps/admin/escrow-scopes/index.d.ts +3 -0
  51. package/dist/apps/admin/escrow-scopes/new/index.d.ts +3 -0
  52. package/dist/apps/admin/index.d.ts +3 -0
  53. package/dist/apps/admin/ingest-queue/index.d.ts +4 -0
  54. package/dist/apps/admin/mailbox-policy/index.d.ts +3 -0
  55. package/dist/apps/admin/mailboxes/[uid].d.ts +7 -0
  56. package/dist/apps/admin/mailboxes/new/index.d.ts +3 -0
  57. package/dist/apps/admin/plugins/index.d.ts +3 -0
  58. package/dist/apps/admin/quarantine/index.d.ts +6 -0
  59. package/dist/apps/admin/retention-policy/index.d.ts +3 -0
  60. package/dist/apps/admin/setup/index.d.ts +3 -0
  61. package/dist/apps/admin/transport-rules/[uid].d.ts +7 -0
  62. package/dist/apps/admin/transport-rules/_transportRuleConfig.d.ts +21 -0
  63. package/dist/apps/admin/transport-rules/index.d.ts +3 -0
  64. package/dist/apps/admin/transport-rules/new/index.d.ts +3 -0
  65. package/dist/apps/escrow/_layout.d.ts +10 -0
  66. package/dist/apps/escrow/audit-log/index.d.ts +9 -0
  67. package/dist/apps/escrow/index.d.ts +3 -0
  68. package/dist/apps/escrow/matters/[uid].d.ts +7 -0
  69. package/dist/apps/escrow/matters/new/index.d.ts +3 -0
  70. package/dist/apps/shared/components/admin/distributionLists/MemberListCard.d.ts +17 -0
  71. package/dist/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.d.ts +32 -0
  72. package/dist/apps/shared/components/admin/layout/AdminShell.d.ts +32 -0
  73. package/dist/apps/shared/components/admin/layout/AdminShell.js +12 -5
  74. package/dist/apps/shared/components/admin/mailboxes/EscrowScopeCard.d.ts +12 -0
  75. package/dist/apps/shared/components/admin/mailboxes/MailboxTable.d.ts +6 -0
  76. package/dist/apps/shared/components/admin/mailboxes/ResourceSettingsCard.d.ts +19 -0
  77. package/dist/apps/shared/components/admin/mailboxes/ShareAccessCard.d.ts +12 -0
  78. package/dist/apps/shared/components/admin/settings/BrandingForm.d.ts +13 -0
  79. package/dist/apps/shared/components/admin/settings/BrandingForm.js +6 -5
  80. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.d.ts +12 -0
  81. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.d.ts +15 -0
  82. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +2 -2
  83. package/dist/apps/shared/components/admin/settings/LoadedSettingsForm.d.ts +9 -0
  84. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.d.ts +19 -0
  85. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.d.ts +13 -0
  86. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +2 -2
  87. package/dist/apps/shared/components/admin/settings/PluginsManager.d.ts +11 -0
  88. package/dist/apps/shared/components/admin/settings/PluginsManager.js +33 -14
  89. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.d.ts +12 -0
  90. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +2 -2
  91. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.d.ts +14 -0
  92. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +1 -1
  93. package/dist/apps/shared/components/admin/setup/SetupWizard.d.ts +36 -0
  94. package/dist/apps/shared/components/admin/setup/SetupWizard.js +14 -10
  95. package/dist/apps/shared/components/admin/signOut.d.ts +23 -0
  96. package/dist/apps/shared/components/admin/usePagedList.d.ts +39 -0
  97. package/dist/apps/shared/components/calendar/CalendarListSidebar.d.ts +26 -0
  98. package/dist/apps/shared/components/calendar/EventModal.d.ts +46 -0
  99. package/dist/apps/shared/components/calendar/MonthView.d.ts +15 -0
  100. package/dist/apps/shared/components/calendar/RecurrenceEditor.d.ts +20 -0
  101. package/dist/apps/shared/components/calendar/ResourcePicker.d.ts +19 -0
  102. package/dist/apps/shared/components/calendar/SplitDayView.d.ts +28 -0
  103. package/dist/apps/shared/components/calendar/TimeGridView.d.ts +17 -0
  104. package/dist/apps/shared/components/calendar/allDay.d.ts +51 -0
  105. package/dist/apps/shared/components/calendar/layout/CalendarShell.d.ts +40 -0
  106. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +2 -2
  107. package/dist/apps/shared/components/contacts/ContactDetailPane.d.ts +23 -0
  108. package/dist/apps/shared/components/contacts/ContactForm.d.ts +20 -0
  109. package/dist/apps/shared/components/contacts/ContactsSidebar.d.ts +40 -0
  110. package/dist/apps/shared/components/contacts/ContactsToolbar.d.ts +25 -0
  111. package/dist/apps/shared/components/contacts/KeyChangeReview.d.ts +40 -0
  112. package/dist/apps/shared/components/contacts/contactKeys.d.ts +29 -0
  113. package/dist/apps/shared/components/contacts/layout/ContactsShell.d.ts +21 -0
  114. package/dist/apps/shared/components/contacts/layout/ContactsShell.js +2 -2
  115. package/dist/apps/shared/components/escrow/layout/EscrowShell.d.ts +25 -0
  116. package/dist/apps/shared/components/forms/StringListField.d.ts +22 -0
  117. package/dist/apps/shared/components/layout/AppShell.d.ts +49 -0
  118. package/dist/apps/shared/components/layout/AppShell.js +15 -13
  119. package/dist/apps/shared/components/layout/BrandingChrome.d.ts +18 -0
  120. package/dist/apps/shared/components/layout/KeyEnrollmentGate.d.ts +51 -0
  121. package/dist/apps/shared/components/layout/MailboxProvisioning.d.ts +13 -0
  122. package/dist/apps/shared/components/layout/RecoveryCodeUnlock.d.ts +66 -0
  123. package/dist/apps/shared/components/layout/UnlockPromptProvider.d.ts +45 -0
  124. package/dist/apps/shared/components/layout/UserMenu.d.ts +23 -0
  125. package/dist/apps/shared/components/mail/ConversationList.d.ts +47 -0
  126. package/dist/apps/shared/components/mail/ConversationList.js +84 -10
  127. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +62 -0
  128. package/dist/apps/shared/components/mail/ConversationThreadPane.js +217 -60
  129. package/dist/apps/shared/components/mail/MailListToolbar.d.ts +55 -0
  130. package/dist/apps/shared/components/mail/MailListToolbar.js +149 -0
  131. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +59 -0
  132. package/dist/apps/shared/components/mail/MailSelectionBar.js +48 -0
  133. package/dist/apps/shared/components/mail/MenuButton.d.ts +71 -0
  134. package/dist/apps/shared/components/mail/MenuButton.js +211 -0
  135. package/dist/apps/shared/components/mail/MessageDetailPane.d.ts +101 -0
  136. package/dist/apps/shared/components/mail/MessageDetailPane.js +126 -129
  137. package/dist/apps/shared/components/mail/MoveToFolderDialog.d.ts +57 -0
  138. package/dist/apps/shared/components/mail/MoveToFolderDialog.js +138 -0
  139. package/dist/apps/shared/components/mail/compose/ComposeContext.d.ts +73 -0
  140. package/dist/apps/shared/components/mail/compose/ComposeContext.js +3 -1
  141. package/dist/apps/shared/components/mail/compose/ComposeToolbar.d.ts +15 -0
  142. package/dist/apps/shared/components/mail/compose/ComposeWindow.d.ts +37 -0
  143. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +52 -20
  144. package/dist/apps/shared/components/mail/compose/EmojiPicker.d.ts +14 -0
  145. package/dist/apps/shared/components/mail/compose/GifPicker.d.ts +13 -0
  146. package/dist/apps/shared/components/mail/compose/RecipientInput.d.ts +36 -0
  147. package/dist/apps/shared/components/mail/compose/RecipientInput.js +203 -0
  148. package/dist/apps/shared/components/mail/compose/RichTextEditor.d.ts +43 -0
  149. package/dist/apps/shared/components/mail/compose/RichTextEditor.js +21 -3
  150. package/dist/apps/shared/components/mail/compose/ScheduleSendPicker.d.ts +16 -0
  151. package/dist/apps/shared/components/mail/compose/composeFlushRegistry.d.ts +27 -0
  152. package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +37 -0
  153. package/dist/apps/shared/components/mail/compose/quotedBody.js +85 -0
  154. package/dist/apps/shared/components/mail/compose/recipients.d.ts +24 -0
  155. package/dist/apps/shared/components/mail/compose/recipients.js +87 -0
  156. package/dist/apps/shared/components/mail/labelMenu.d.ts +97 -0
  157. package/dist/apps/shared/components/mail/labelMenu.js +134 -0
  158. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +65 -0
  159. package/dist/apps/shared/components/mail/layout/MailShell.js +17 -5
  160. package/dist/apps/shared/components/mail/listPreferences.d.ts +101 -0
  161. package/dist/apps/shared/components/mail/listPreferences.js +186 -0
  162. package/dist/apps/shared/components/mail/pinnedSigners.d.ts +33 -0
  163. package/dist/apps/shared/components/mail/verificationSeals.d.ts +22 -0
  164. package/dist/apps/shared/components/mail/writableMailboxes.d.ts +15 -0
  165. package/dist/apps/shared/components/rules/RuleBuilder.d.ts +70 -0
  166. package/dist/apps/shared/components/settings/layout/SettingsShell.d.ts +41 -0
  167. package/dist/apps/shared/components/settings/layout/SettingsShell.js +19 -10
  168. package/dist/apps/shared/components/tasks/TasksSidebar.d.ts +41 -0
  169. package/dist/apps/shared/components/tasks/TasksToolbar.d.ts +14 -0
  170. package/dist/apps/shared/components/tasks/layout/TasksShell.d.ts +24 -0
  171. package/dist/apps/shared/components/tasks/layout/TasksShell.js +2 -2
  172. package/dist/apps/shared/mail/findWellKnownFolderUid.d.ts +5 -0
  173. package/dist/apps/shared/mail/listAllPages.d.ts +17 -0
  174. package/dist/apps/shared/plugins/pluginNav.d.ts +39 -0
  175. package/dist/apps/shared/plugins/pluginNav.js +33 -0
  176. package/dist/apps/shared/search/LocalIndexLifecycle.d.ts +13 -0
  177. package/dist/apps/shared/search/localIndexBlockCipher.d.ts +36 -0
  178. package/dist/apps/shared/search/localIndexBuilder.d.ts +85 -0
  179. package/dist/apps/shared/search/localIndexKey.d.ts +4 -0
  180. package/dist/apps/shared/search/localIndexRpcClient.d.ts +71 -0
  181. package/dist/apps/shared/search/localIndexRpcClient.js +3 -1
  182. package/dist/apps/shared/search/localIndexSchema.d.ts +111 -0
  183. package/dist/apps/shared/search/localIndexSizePreference.d.ts +27 -0
  184. package/dist/apps/shared/search/localIndexStorage.d.ts +28 -0
  185. package/dist/apps/shared/search/localIndexVFS.d.ts +101 -0
  186. package/dist/apps/shared/search/localIndexWorker.d.ts +145 -0
  187. package/dist/apps/shared/search/searchTier2.d.ts +30 -0
  188. package/dist/apps/shared/styles/app.css +28 -5
  189. package/dist/apps/www/_404.d.ts +2 -0
  190. package/dist/apps/www/_500.d.ts +2 -0
  191. package/dist/apps/www/_layout.d.ts +14 -0
  192. package/dist/apps/www/calendar/index.d.ts +3 -0
  193. package/dist/apps/www/contacts/[uid].d.ts +13 -0
  194. package/dist/apps/www/contacts/index.d.ts +3 -0
  195. package/dist/apps/www/index.d.ts +3 -0
  196. package/dist/apps/www/index.js +506 -112
  197. package/dist/apps/www/messages/[uid].d.ts +11 -0
  198. package/dist/apps/www/messages/[uid].js +2 -3
  199. package/dist/apps/www/settings/auto-reply/index.d.ts +4 -0
  200. package/dist/apps/www/settings/encryption/index.d.ts +7 -0
  201. package/dist/apps/www/settings/filters/[uid].d.ts +8 -0
  202. package/dist/apps/www/settings/filters/_mailFilterRuleConfig.d.ts +11 -0
  203. package/dist/apps/www/settings/filters/index.d.ts +4 -0
  204. package/dist/apps/www/settings/filters/new/index.d.ts +4 -0
  205. package/dist/apps/www/settings/labels/index.d.ts +4 -0
  206. package/dist/apps/www/settings/privacy/index.d.ts +4 -0
  207. package/dist/apps/www/settings/read-receipts/index.d.ts +4 -0
  208. package/dist/apps/www/settings/sharing/index.d.ts +4 -0
  209. package/dist/apps/www/settings/signatures/[uid].d.ts +8 -0
  210. package/dist/apps/www/settings/signatures/index.d.ts +4 -0
  211. package/dist/apps/www/settings/signatures/new/index.d.ts +4 -0
  212. package/dist/apps/www/settings/signatures/signatureDefaults.d.ts +10 -0
  213. package/dist/apps/www/tasks/index.d.ts +3 -0
  214. package/package.json +3 -3
  215. package/apps/shared/components/booking/AvailabilityEditor.tsx +0 -118
  216. package/apps/www/settings/booking-types/[uid].tsx +0 -306
  217. package/apps/www/settings/booking-types/index.tsx +0 -98
  218. package/apps/www/settings/booking-types/new/index.tsx +0 -212
  219. package/apps/www/settings/focused-inbox/index.tsx +0 -150
  220. package/dist/apps/shared/components/booking/AvailabilityEditor.js +0 -45
  221. package/dist/apps/www/settings/booking-types/[uid].js +0 -134
  222. package/dist/apps/www/settings/booking-types/index.js +0 -29
  223. package/dist/apps/www/settings/booking-types/new/index.js +0 -86
  224. package/dist/apps/www/settings/focused-inbox/index.js +0 -71
@@ -1,1235 +1,1288 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { FormEvent, useCallback, useEffect, useRef, useState } from "react";
6
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
- import {
8
- addPlugin,
9
- expectedPlanOf,
10
- getPluginStatus,
11
- getPluginUpdates,
12
- listPluginNamespaces,
13
- listPlugins,
14
- lookupPluginPackage,
15
- planPluginChange,
16
- Plugin,
17
- PluginChangePlan,
18
- PluginInstanceStatus,
19
- PluginNamespace,
20
- PluginRegistryLookup,
21
- PluginSearchResult,
22
- PluginSettingDefinition,
23
- PluginSettingValue,
24
- PluginStatus,
25
- PluginUpdateInfo,
26
- removePlugin,
27
- searchPlugins,
28
- updatePlugin,
29
- } from "@rapidmx/react-shared/admin/pluginsApi.js";
30
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
31
- import Button from "@rapidmx/react-shared/components/buttons/Button.js";
32
- import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
33
-
34
- const INPUT_CLASS =
35
- "w-full text-sm py-2 px-3 border border-border rounded-sm bg-surface text-text focus:outline-none focus:border-primary";
36
-
37
- /** How often status is refreshed while server copies are still applying a change. */
38
- const PENDING_POLL_MS = 5000;
39
-
40
- /** How long status keeps being polled after a saved change, since servers may not have noticed it yet. */
41
- const AFTER_CHANGE_POLL_MS = 2 * 60 * 1000;
42
-
43
- /** The longest wait between retries while no status has ever been read. */
44
- const MAX_STATUS_RETRY_MS = 60 * 1000;
45
-
46
- function errorMessage(err: unknown, fallback: string): string {
47
- return err instanceof ApiRequestError ? err.message : fallback;
48
- }
49
-
50
- /** Runs `action`, resolving why it failed, or `null`. */
51
- async function attempt(action: () => Promise<void>, failure: string): Promise<string | null> {
52
- try {
53
- await action();
54
- return null;
55
- } catch (err) {
56
- return errorMessage(err, failure);
57
- }
58
- }
59
-
60
- /** A change waiting for the administrator to confirm the other plugins it also installs or enables. */
61
- interface PendingChange {
62
- displayName: string;
63
- plan: PluginChangePlan;
64
- apply: (plan: PluginChangePlan) => Promise<void>;
65
- failure: string;
66
- /** The installed plugin being changed, which stays busy while the change waits for confirmation. */
67
- uid?: string;
68
- }
69
-
70
- /** Installed plugins with their rollout status, and every plugin action - shared by the Plugins page and the
71
- * setup wizard. */
72
- export default function PluginsManager() {
73
- const [plugins, setPlugins] = useState<Plugin[]>([]);
74
- const [status, setStatus] = useState<PluginStatus | null>(null);
75
- /** Set when the last status refresh failed, so what's shown may be out of date. */
76
- const [statusStale, setStatusStale] = useState(false);
77
- /** When polling started by a saved change stops (epoch ms), or 0 when there's none. */
78
- const [pollUntil, setPollUntil] = useState(0);
79
- const [updates, setUpdates] = useState<Map<string, PluginUpdateInfo>>(new Map());
80
- const [loading, setLoading] = useState(true);
81
- const [error, setError] = useState<string | null>(null);
82
- /** The installed plugin whose enable just failed, offered a retry next to `error`. */
83
- const [retryEnableUid, setRetryEnableUid] = useState<string | null>(null);
84
- const [adding, setAdding] = useState(false);
85
- const [upgrading, setUpgrading] = useState<Plugin | null>(null);
86
- const [configuring, setConfiguring] = useState<Plugin | null>(null);
87
- const [removing, setRemoving] = useState<Plugin | null>(null);
88
- const [confirming, setConfirming] = useState<PendingChange | null>(null);
89
- /** Installed plugins with an action under way. */
90
- const [busyUids, setBusyUids] = useState<ReadonlySet<string>>(new Set());
91
- /** Set when re-reading the list after a change failed, so rows may not show what that change also did. */
92
- const [listStale, setListStale] = useState(false);
93
- /** How many times status has been retried while none has ever been read. */
94
- const [statusRetries, setStatusRetries] = useState(0);
95
- const statusRequest = useRef<Promise<void> | null>(null);
96
-
97
- const setBusy = (uid: string, busy: boolean) =>
98
- setBusyUids((prev) => {
99
- const next = new Set(prev);
100
- if (busy) {
101
- next.add(uid);
102
- } else {
103
- next.delete(uid);
104
- }
105
- return next;
106
- });
107
-
108
- const refreshStatus = useCallback(() => {
109
- // One read at a time: a poll that comes due while a slow read is still running shares it.
110
- statusRequest.current ??= getPluginStatus()
111
- .then((next) => {
112
- setStatus(next);
113
- setStatusStale(false);
114
- })
115
- // Status is advisory - a failure to read it shouldn't hide the plugin list, or lose the last status read.
116
- .catch(() => setStatusStale(true))
117
- .finally(() => {
118
- statusRequest.current = null;
119
- });
120
- return statusRequest.current;
121
- }, []);
122
-
123
- const refreshUpdates = useCallback(() => {
124
- // Also advisory: a registry that can't be reached just means no update badges.
125
- return getPluginUpdates()
126
- .then((list) => setUpdates(new Map(list.map((info) => [info.uid, info]))))
127
- .catch(() => setUpdates(new Map()));
128
- }, []);
129
-
130
- /** Re-reads the list, for changes that also installed or enabled other plugins. */
131
- const reload = useCallback(() => {
132
- return listPlugins()
133
- .then((list) => {
134
- setPlugins(list);
135
- setListStale(false);
136
- })
137
- .catch(() => setListStale(true));
138
- }, []);
139
-
140
- useEffect(() => {
141
- Promise.all([listPlugins(), refreshStatus()])
142
- .then(([list]) => {
143
- setPlugins(list);
144
- void refreshUpdates();
145
- })
146
- .catch((err) => setError(errorMessage(err, "Could not load plugins.")))
147
- .finally(() => setLoading(false));
148
- }, [refreshStatus, refreshUpdates]);
149
-
150
- const pending: boolean = !!status && status.instances.some((instance) => instance.hash !== status.hash);
151
- useEffect(() => {
152
- if (!pending && pollUntil === 0) {
153
- return;
154
- }
155
- const timer = setInterval(() => void refreshStatus(), PENDING_POLL_MS);
156
- // Polling for a saved change ends after a while; a rollout that's under way keeps it going.
157
- const stop = pollUntil > 0 ? setTimeout(() => setPollUntil(0), Math.max(0, pollUntil - Date.now())) : undefined;
158
- return () => {
159
- clearInterval(timer);
160
- clearTimeout(stop);
161
- };
162
- }, [pending, pollUntil, refreshStatus]);
163
-
164
- // With no status read at all there's nothing pending to poll for, so keep retrying - less often each time.
165
- const neverRead: boolean = !status && statusStale;
166
- useEffect(() => {
167
- if (!neverRead) {
168
- return;
169
- }
170
- const timer = setTimeout(
171
- () => void refreshStatus().then(() => setStatusRetries((n) => n + 1)),
172
- Math.min(PENDING_POLL_MS * 2 ** statusRetries, MAX_STATUS_RETRY_MS),
173
- );
174
- return () => clearTimeout(timer);
175
- }, [neverRead, statusRetries, refreshStatus]);
176
-
177
- /** Re-reads status, and keeps doing so for a while, since saving starts a rollout servers pick up shortly. */
178
- function watchRollout() {
179
- setPollUntil(Date.now() + AFTER_CHANGE_POLL_MS);
180
- void refreshStatus();
181
- }
182
-
183
- /** Applies saved changes locally and re-reads status and updates, since saving starts a rollout. */
184
- function applied(...changed: Plugin[]) {
185
- setPlugins((prev) => {
186
- let next = prev;
187
- for (const updated of changed) {
188
- const exists = next.some((plugin) => plugin.uid === updated.uid);
189
- next = exists ? next.map((plugin) => (plugin.uid === updated.uid ? updated : plugin)) : [...next, updated];
190
- }
191
- return [...next].sort((a, b) => a.name.localeCompare(b.name));
192
- });
193
- watchRollout();
194
- void refreshUpdates();
195
- }
196
-
197
- /** Runs an action on an installed plugin's row, which is busy meanwhile, and shows why it failed. */
198
- async function onRow(plugin: Plugin, action: () => Promise<string | null>) {
199
- setBusy(plugin.uid, true);
200
- setError(null);
201
- setRetryEnableUid(null);
202
- const problem = await action();
203
- if (problem) {
204
- setError(problem);
205
- }
206
- // A change waiting for confirmation keeps the row busy by itself, until the confirmation closes.
207
- setBusy(plugin.uid, false);
208
- }
209
-
210
- function toggle(plugin: Plugin) {
211
- const displayName: string = plugin.manifest.displayName;
212
- if (plugin.enabled) {
213
- return onRow(plugin, () =>
214
- attempt(async () => applied(await updatePlugin(plugin.uid, { version: plugin.version, enabled: false })), `Could not disable ${displayName}.`),
215
- );
216
- }
217
- // Enabling a plugin also installs or enables the plugins it requires, so it's previewed like any other change.
218
- // The installed version is planned from its stored manifest, so this doesn't need the registry. A preview that
219
- // fails is never skipped - enabling without one could install or enable other plugins the administrator never
220
- // saw - so the failure is shown with a retry instead.
221
- return onRow(plugin, async () => {
222
- const problem = await planned(
223
- plugin.name,
224
- plugin.packageVersion,
225
- displayName,
226
- async (plan) => {
227
- applied(await updatePlugin(plugin.uid, { version: plugin.version, enabled: true, expectedPlan: expectedPlanOf(plan) }));
228
- if (plan.install.length > 0 || plan.enable.length > 0) {
229
- void reload();
230
- }
231
- },
232
- `Could not enable ${displayName}.`,
233
- { uid: plugin.uid },
234
- );
235
- if (problem) {
236
- setRetryEnableUid(plugin.uid);
237
- }
238
- return problem;
239
- });
240
- }
241
-
242
- /**
243
- * Checks what installing or changing a plugin also takes before doing it. Resolves why it can't be done, or `null`
244
- * once it's done - or, when it also installs or enables other plugins, once they're shown for confirmation.
245
- */
246
- async function planned(
247
- name: string,
248
- packageVersion: string,
249
- displayName: string,
250
- apply: (plan: PluginChangePlan) => Promise<void>,
251
- failure: string,
252
- options: { uid?: string } = {},
253
- ): Promise<string | null> {
254
- let plan: PluginChangePlan;
255
- try {
256
- plan = await planPluginChange(name, packageVersion);
257
- } catch (err) {
258
- return errorMessage(err, failure);
259
- }
260
- if (plan.conflicts.length > 0) {
261
- return `${displayName} ${plan.plugin.version} can't be installed. ${plan.conflicts.join(" ")}`;
262
- }
263
- if (plan.install.length > 0 || plan.enable.length > 0) {
264
- setConfirming({ displayName, plan, apply, failure, uid: options.uid });
265
- return null;
266
- }
267
- return attempt(() => apply(plan), failure);
268
- }
269
-
270
- function install(name: string, packageVersion: string, displayName: string) {
271
- return planned(
272
- name,
273
- packageVersion,
274
- displayName,
275
- async (plan) => {
276
- const result = await addPlugin(name, packageVersion, expectedPlanOf(plan));
277
- applied(...result.dependencies, result.plugin);
278
- },
279
- `Could not install ${displayName}.`,
280
- );
281
- }
282
-
283
- function changeVersion(plugin: Plugin, packageVersion: string) {
284
- const failure = `Could not upgrade ${plugin.manifest.displayName}.`;
285
- if (!plugin.enabled) {
286
- // A disabled plugin stays disabled, so nothing it requires is installed or enabled - there's nothing to preview.
287
- return attempt(async () => applied(await updatePlugin(plugin.uid, { version: plugin.version, packageVersion })), failure);
288
- }
289
- return planned(
290
- plugin.name,
291
- packageVersion,
292
- plugin.manifest.displayName,
293
- async (plan) => {
294
- applied(await updatePlugin(plugin.uid, { version: plugin.version, packageVersion, expectedPlan: expectedPlanOf(plan) }));
295
- if (plan.install.length > 0 || plan.enable.length > 0) {
296
- void reload();
297
- }
298
- },
299
- failure,
300
- { uid: plugin.uid },
301
- );
302
- }
303
-
304
- function upgrade(plugin: Plugin, packageVersion: string) {
305
- return onRow(plugin, () => changeVersion(plugin, packageVersion));
306
- }
307
-
308
- // Retried against the plugin as it's listed now (a newer version, or already enabled elsewhere, hides the retry).
309
- const retryEnable: Plugin | undefined = plugins.find((plugin) => plugin.uid === retryEnableUid && !plugin.enabled);
310
-
311
- const displayNameOf = (name: string): string => plugins.find((plugin) => plugin.name === name)?.manifest.displayName ?? name;
312
-
313
- return (
314
- <>
315
- <div className="flex items-center justify-between mb-2">
316
- <h1 className="text-xl font-bold uppercase tracking-wide">Plugins</h1>
317
- <Button type="button" variant="secondary" className="!w-auto" onClick={() => setAdding(true)}>
318
- Add by name
319
- </Button>
320
- </div>
321
- <p className="text-sm text-text-muted mb-5 max-w-3xl">
322
- Plugins add protocols and features to every server. Changes are applied by restarting the servers
323
- one at a time, so mail keeps flowing. Plugins run with full access to the server, so only add ones
324
- you trust.
325
- </p>
326
-
327
- {error && (
328
- <Alert>
329
- {error}
330
- {retryEnable && (
331
- <>
332
- {" "}
333
- <Button
334
- type="button"
335
- variant="text"
336
- className="!w-auto !p-0"
337
- onClick={() => void toggle(retryEnable)}
338
- >
339
- Try again
340
- </Button>
341
- </>
342
- )}
343
- </Alert>
344
- )}
345
- <RolloutBanner status={status} />
346
- {statusStale && status && (
347
- <p className="mb-4 text-xs text-text-muted">Couldn&apos;t refresh server status. Showing the last status reported.</p>
348
- )}
349
- {listStale && (
350
- <p className="mb-4 text-xs text-text-muted">
351
- Couldn&apos;t re-read the plugin list, so it may be out of date.{" "}
352
- <Button type="button" variant="text" className="!w-auto !p-0 !text-xs" onClick={() => void reload()}>
353
- Retry
354
- </Button>
355
- </p>
356
- )}
357
-
358
- <h2 className="text-sm font-bold uppercase tracking-wide mb-2">Installed plugins</h2>
359
- {loading ? (
360
- <p className="text-sm text-text-muted">Loading&hellip;</p>
361
- ) : plugins.length === 0 ? (
362
- <p className="text-sm text-text-muted">No plugins installed.</p>
363
- ) : (
364
- <div className="overflow-x-auto">
365
- <table className="w-full text-sm border-collapse">
366
- <thead>
367
- <tr>
368
- {["Plugin", "Version", "State", "Servers", ""].map((h) => (
369
- <th
370
- key={h}
371
- className="text-left text-xs uppercase tracking-wide text-text-muted py-2 px-2.5 border-b border-border"
372
- >
373
- {h}
374
- </th>
375
- ))}
376
- </tr>
377
- </thead>
378
- <tbody>
379
- {plugins.map((plugin) => {
380
- const update: PluginUpdateInfo | undefined = updates.get(plugin.uid);
381
- const latest: string | undefined = update?.updateAvailable ? update.latestVersion : undefined;
382
- const busy: boolean = busyUids.has(plugin.uid) || confirming?.uid === plugin.uid;
383
- const requires: string[] = Object.keys(plugin.manifest.requires ?? {}).map(displayNameOf);
384
- const requiredBy: string[] = plugins
385
- .filter((other) => other.uid !== plugin.uid && other.manifest.requires?.[plugin.name] !== undefined)
386
- .map((other) => other.manifest.displayName);
387
- return (
388
- <tr key={plugin.uid}>
389
- <td className="py-2.5 px-2.5 border-b border-border align-top">
390
- <div className="font-semibold">{plugin.manifest.displayName}</div>
391
- <div className="text-xs text-text-muted">{plugin.name}</div>
392
- {plugin.manifest.description && (
393
- <div className="text-xs text-text-muted mt-1 max-w-md">{plugin.manifest.description}</div>
394
- )}
395
- {requires.length > 0 && <div className="text-xs text-text-muted mt-1">Requires: {requires.join(", ")}</div>}
396
- {requiredBy.length > 0 && (
397
- <div className="text-xs text-text-muted mt-1">Required by: {requiredBy.join(", ")}</div>
398
- )}
399
- </td>
400
- <td className="py-2.5 px-2.5 border-b border-border align-top">
401
- <div>{plugin.packageVersion}</div>
402
- {latest && (
403
- <div className="mt-1 flex flex-col items-start gap-1">
404
- <span className="text-xs font-semibold text-primary-dark">Update available: {latest}</span>
405
- <Button
406
- type="button"
407
- variant="secondary"
408
- className="!w-auto !py-1 !px-2 !text-xs"
409
- aria-label={`Upgrade ${plugin.manifest.displayName} to ${latest}`}
410
- disabled={busy}
411
- onClick={() => void upgrade(plugin, latest)}
412
- >
413
- Upgrade
414
- </Button>
415
- </div>
416
- )}
417
- </td>
418
- <td className="py-2.5 px-2.5 border-b border-border align-top">
419
- {plugin.enabled ? (
420
- <span className="text-xs font-bold uppercase tracking-wide py-0.5 px-2 rounded-pill bg-success text-white">
421
- Enabled
422
- </span>
423
- ) : (
424
- <span className="text-xs font-bold uppercase tracking-wide py-0.5 px-2 rounded-pill bg-surface-alt text-text-muted">
425
- Disabled
426
- </span>
427
- )}
428
- </td>
429
- <td className="py-2.5 px-2.5 border-b border-border align-top">
430
- <PluginStatusCell plugin={plugin} status={status} />
431
- </td>
432
- <td className="py-2.5 px-2.5 border-b border-border align-top text-right whitespace-nowrap">
433
- <Button
434
- variant="text"
435
- type="button"
436
- className="!w-auto"
437
- aria-label={`${plugin.enabled ? "Disable" : "Enable"} ${plugin.manifest.displayName}`}
438
- disabled={busy}
439
- onClick={() => void toggle(plugin)}
440
- >
441
- {plugin.enabled ? "Disable" : "Enable"}
442
- </Button>
443
- {(plugin.manifest.settings ?? []).length > 0 && (
444
- <Button variant="text" type="button" className="!w-auto" onClick={() => setConfiguring(plugin)}>
445
- Settings
446
- </Button>
447
- )}
448
- <Button variant="text" type="button" className="!w-auto" onClick={() => setUpgrading(plugin)}>
449
- Change version
450
- </Button>
451
- <Button variant="text" type="button" className="!w-auto" onClick={() => setRemoving(plugin)}>
452
- Uninstall
453
- </Button>
454
- </td>
455
- </tr>
456
- );
457
- })}
458
- </tbody>
459
- </table>
460
- </div>
461
- )}
462
-
463
- <PluginBrowser
464
- plugins={plugins}
465
- onInstall={(result) => install(result.name, result.version, result.name)}
466
- // The browser only offers an upgrade for a result it matched to one of these same `plugins`.
467
- onUpgrade={(uid, packageVersion) => upgrade(plugins.find((p) => p.uid === uid)!, packageVersion)}
468
- />
469
-
470
- <AddPluginModal
471
- open={adding}
472
- onClose={() => setAdding(false)}
473
- onAdd={async (name, packageVersion, displayName) => {
474
- const problem = await install(name, packageVersion, displayName);
475
- if (!problem) {
476
- setAdding(false);
477
- }
478
- return problem;
479
- }}
480
- />
481
- {upgrading && (
482
- <ChangeVersionModal
483
- plugin={upgrading}
484
- onClose={() => setUpgrading(null)}
485
- onSave={async (packageVersion) => {
486
- const problem = await changeVersion(upgrading, packageVersion);
487
- if (!problem) {
488
- setUpgrading(null);
489
- }
490
- return problem;
491
- }}
492
- />
493
- )}
494
- {confirming && (
495
- <ConfirmDependenciesModal
496
- change={confirming}
497
- displayNameOf={displayNameOf}
498
- onClose={() => setConfirming(null)}
499
- onDone={() => setConfirming(null)}
500
- />
501
- )}
502
- {configuring && (
503
- <SettingsModal
504
- plugin={configuring}
505
- onClose={() => setConfiguring(null)}
506
- onSaved={(plugin) => {
507
- setConfiguring(null);
508
- applied(plugin);
509
- }}
510
- />
511
- )}
512
- {removing && (
513
- <RemoveModal
514
- plugin={removing}
515
- onClose={() => setRemoving(null)}
516
- onRemoved={() => {
517
- const uid = removing.uid;
518
- setRemoving(null);
519
- setPlugins((prev) => prev.filter((plugin) => plugin.uid !== uid));
520
- watchRollout();
521
- }}
522
- />
523
- )}
524
- </>
525
- );
526
- }
527
-
528
- const ALL_NAMESPACES = "";
529
-
530
- /** Searches the configured namespaces' registries for plugin packages, with install and upgrade actions. */
531
- function PluginBrowser({
532
- plugins,
533
- onInstall,
534
- onUpgrade,
535
- }: {
536
- plugins: Plugin[];
537
- /** Resolves why the plugin couldn't be installed, or `null`. */
538
- onInstall: (result: PluginSearchResult) => Promise<string | null>;
539
- onUpgrade: (uid: string, packageVersion: string) => Promise<void>;
540
- }) {
541
- const [namespaces, setNamespaces] = useState<PluginNamespace[]>([]);
542
- const [namespace, setNamespace] = useState(ALL_NAMESPACES);
543
- const [results, setResults] = useState<PluginSearchResult[] | null>(null);
544
- const [searching, setSearching] = useState(false);
545
- const [busyName, setBusyName] = useState<string | null>(null);
546
- const [error, setError] = useState<string | null>(null);
547
-
548
- useEffect(() => {
549
- listPluginNamespaces()
550
- .then(setNamespaces)
551
- .catch(() => setNamespaces([]));
552
- }, []);
553
-
554
- async function search(e: FormEvent) {
555
- e.preventDefault();
556
- setSearching(true);
557
- setError(null);
558
- try {
559
- setResults(await searchPlugins(namespace || undefined));
560
- } catch (err) {
561
- setResults(null);
562
- setError(errorMessage(err, "Could not search for plugins."));
563
- } finally {
564
- setSearching(false);
565
- }
566
- }
567
-
568
- // Keep results in step with installs and upgrades made anywhere on the page.
569
- const rows: PluginSearchResult[] = (results ?? []).map((result) => {
570
- const installed: Plugin | undefined = plugins.find((plugin) => plugin.name === result.name);
571
- return {
572
- ...result,
573
- installedUid: installed?.uid,
574
- installedVersion: installed?.packageVersion,
575
- updateAvailable: !!installed && installed.packageVersion !== result.version && result.updateAvailable,
576
- };
577
- });
578
-
579
- async function install(result: PluginSearchResult) {
580
- setBusyName(result.name);
581
- setError(null);
582
- setError(await onInstall(result));
583
- setBusyName(null);
584
- }
585
-
586
- async function upgrade(result: PluginSearchResult) {
587
- setBusyName(result.name);
588
- try {
589
- await onUpgrade(result.installedUid!, result.version);
590
- } finally {
591
- setBusyName(null);
592
- }
593
- }
594
-
595
- return (
596
- <section aria-labelledby="plugin-browser-title" className="mt-8">
597
- <h2 id="plugin-browser-title" className="text-sm font-bold uppercase tracking-wide mb-2">
598
- Find plugins
599
- </h2>
600
- <form onSubmit={(e) => void search(e)} className="flex flex-wrap gap-2 items-end mb-3">
601
- <label className="flex flex-col gap-1.5 text-sm">
602
- <span className="font-semibold">Namespace</span>
603
- <select aria-label="Namespace" className={INPUT_CLASS} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
604
- <option value={ALL_NAMESPACES}>All namespaces</option>
605
- {namespaces.map((ns) => (
606
- <option key={ns.name} value={ns.name}>
607
- {ns.name}
608
- </option>
609
- ))}
610
- </select>
611
- </label>
612
- <Button type="submit" className="!w-auto" loading={searching} disabled={searching}>
613
- Search
614
- </Button>
615
- </form>
616
- {error && <Alert>{error}</Alert>}
617
- {results !== null &&
618
- (rows.length === 0 ? (
619
- <p className="text-sm text-text-muted">No plugins found.</p>
620
- ) : (
621
- <div className="overflow-x-auto">
622
- <table className="w-full text-sm border-collapse">
623
- <thead>
624
- <tr>
625
- {["Package", "Latest version", "Status", ""].map((h) => (
626
- <th
627
- key={h}
628
- className="text-left text-xs uppercase tracking-wide text-text-muted py-2 px-2.5 border-b border-border"
629
- >
630
- {h}
631
- </th>
632
- ))}
633
- </tr>
634
- </thead>
635
- <tbody>
636
- {rows.map((result) => (
637
- <tr key={result.name}>
638
- <td className="py-2.5 px-2.5 border-b border-border align-top">
639
- <div className="font-semibold">{result.name}</div>
640
- {result.description && <div className="text-xs text-text-muted max-w-md">{result.description}</div>}
641
- </td>
642
- <td className="py-2.5 px-2.5 border-b border-border align-top">{result.version}</td>
643
- <td className="py-2.5 px-2.5 border-b border-border align-top text-text-muted">
644
- {result.updateAvailable
645
- ? `Installed ${result.installedVersion} - update available`
646
- : result.installedUid
647
- ? `Installed ${result.installedVersion}`
648
- : result.allowed
649
- ? "Not installed"
650
- : "Not allowed on this server"}
651
- </td>
652
- <td className="py-2.5 px-2.5 border-b border-border align-top text-right">
653
- {result.updateAvailable ? (
654
- <Button
655
- type="button"
656
- variant="secondary"
657
- className="!w-auto"
658
- aria-label={`Upgrade ${result.name} to ${result.version}`}
659
- disabled={busyName === result.name}
660
- onClick={() => void upgrade(result)}
661
- >
662
- Upgrade
663
- </Button>
664
- ) : (
665
- !result.installedUid &&
666
- result.allowed && (
667
- <Button
668
- type="button"
669
- className="!w-auto"
670
- aria-label={`Install ${result.name}`}
671
- loading={busyName === result.name}
672
- disabled={busyName === result.name}
673
- onClick={() => void install(result)}
674
- >
675
- Install
676
- </Button>
677
- )
678
- )}
679
- </td>
680
- </tr>
681
- ))}
682
- </tbody>
683
- </table>
684
- </div>
685
- ))}
686
- </section>
687
- );
688
- }
689
-
690
- /** Name a server reports an error under when it isn't about any single plugin (e.g. the plugin set as a whole failed). */
691
- const SERVER_WIDE_ERROR_NAME = "*";
692
-
693
- /**
694
- * Shown while any server copy hasn't applied the saved plugin set yet, when one is in safe mode, or when one reports a
695
- * server-wide plugin error - those match no plugin row, so without this they'd never be shown.
696
- */
697
- function RolloutBanner({ status }: { status: PluginStatus | null }) {
698
- if (!status || status.instances.length === 0) {
699
- return null;
700
- }
701
- const behind = status.instances.filter((instance) => instance.hash !== status.hash).length;
702
- const safeMode = status.instances.filter((instance) => instance.safeMode);
703
- const serverWideErrors = status.instances.flatMap((instance) =>
704
- instance.errors
705
- .filter((entry) => entry.name === SERVER_WIDE_ERROR_NAME)
706
- .map((entry) => `${instance.instance}: ${entry.message}`),
707
- );
708
- return (
709
- <>
710
- {serverWideErrors.length > 0 && (
711
- <Alert>
712
- Plugins couldn&rsquo;t be loaded:
713
- <ul className="list-disc pl-5 mt-1">
714
- {serverWideErrors.map((message) => (
715
- <li key={message} className="break-words">
716
- {message}
717
- </li>
718
- ))}
719
- </ul>
720
- </Alert>
721
- )}
722
- {behind > 0 && (
723
- <p role="status" className="mb-4 text-sm py-2 px-3 rounded-sm bg-surface-alt text-text">
724
- Applying changes: {status.instances.length - behind} of {status.instances.length}{" "}
725
- {status.instances.length === 1 ? "server" : "servers"} updated. Servers restart one at a time.
726
- </p>
727
- )}
728
- {safeMode.length > 0 && (
729
- <Alert>
730
- {safeMode.map((instance) => instance.instance).join(", ")} started without any plugins because recent
731
- starts failed. Fix or disable the failing plugin, and the server will pick up the change.
732
- </Alert>
733
- )}
734
- </>
735
- );
736
- }
737
-
738
- function PluginStatusCell({ plugin, status }: { plugin: Plugin; status: PluginStatus | null }) {
739
- if (!plugin.enabled) {
740
- return <span className="text-text-muted">Disabled</span>;
741
- }
742
- if (!status || status.instances.length === 0) {
743
- return <span className="text-text-muted">Unknown</span>;
744
- }
745
- const current: PluginInstanceStatus[] = status.instances.filter((instance) => instance.hash === status.hash);
746
- const loaded = current.filter((instance) =>
747
- instance.loaded.some((entry) => entry.name === plugin.name && entry.version === plugin.packageVersion),
748
- ).length;
749
- const errors = current.flatMap((instance) =>
750
- instance.errors.filter((entry) => entry.name === plugin.name).map((entry) => `${instance.instance}: ${entry.message}`),
751
- );
752
- return (
753
- <div>
754
- <span className={loaded === status.instances.length ? "text-success font-medium" : "text-text-muted"}>
755
- Loaded on {loaded} of {status.instances.length} {status.instances.length === 1 ? "server" : "servers"}
756
- </span>
757
- {errors.map((message) => (
758
- <div key={message} className="text-xs text-danger mt-1">
759
- {message}
760
- </div>
761
- ))}
762
- </div>
763
- );
764
- }
765
-
766
- function AddPluginModal({
767
- open,
768
- onClose,
769
- onAdd,
770
- }: {
771
- open: boolean;
772
- onClose: () => void;
773
- /** Resolves why the plugin couldn't be added, or `null`. */
774
- onAdd: (name: string, packageVersion: string, displayName: string) => Promise<string | null>;
775
- }) {
776
- const [name, setName] = useState("");
777
- const [lookup, setLookup] = useState<PluginRegistryLookup | null>(null);
778
- const [selectedVersion, setSelectedVersion] = useState("");
779
- const [error, setError] = useState<string | null>(null);
780
- const [busy, setBusy] = useState(false);
781
- const [looking, setLooking] = useState(false);
782
- /** Identifies the latest lookup, so a slower earlier response can't replace what it found. */
783
- const lookupToken = useRef(0);
784
- /** Identifies each time the dialog is opened, so an add that finishes after it was closed can't show its result. */
785
- const openToken = useRef(0);
786
-
787
- /** Forgets any lookup still in flight. */
788
- function invalidateLookup() {
789
- lookupToken.current++;
790
- setLooking(false);
791
- }
792
-
793
- useEffect(() => {
794
- if (!open) {
795
- openToken.current++;
796
- invalidateLookup();
797
- setName("");
798
- setLookup(null);
799
- setSelectedVersion("");
800
- setError(null);
801
- setBusy(false);
802
- }
803
- }, [open]);
804
-
805
- /** Looks up `packageName` at `packageVersion` (default: latest). `previous` is what a version change started
806
- * from - kept, with the failure in place of its manifest, when that version can't be read. */
807
- async function runLookup(packageName: string, packageVersion?: string, previous?: PluginRegistryLookup) {
808
- const token = ++lookupToken.current;
809
- setLooking(true);
810
- setError(null);
811
- try {
812
- const found = await lookupPluginPackage(packageName, packageVersion);
813
- if (token === lookupToken.current) {
814
- setLookup(found);
815
- setSelectedVersion(found.selected.version);
816
- }
817
- } catch (err) {
818
- if (token !== lookupToken.current) {
819
- return;
820
- }
821
- const message = errorMessage(err, "Could not look that package up.");
822
- if (previous && packageVersion) {
823
- setLookup({ ...previous, selected: { ...previous.selected, version: packageVersion, manifest: message } });
824
- } else {
825
- setLookup(null);
826
- setError(message);
827
- }
828
- } finally {
829
- if (token === lookupToken.current) {
830
- setLooking(false);
831
- }
832
- }
833
- }
834
-
835
- function find(e: FormEvent) {
836
- e.preventDefault();
837
- if (!name.trim()) {
838
- setError("Enter a package name.");
839
- return;
840
- }
841
- void runLookup(name.trim());
842
- }
843
-
844
- function chooseVersion(version: string) {
845
- setSelectedVersion(version);
846
- // The manifest shown, and whether it's a loadable plugin, depend on the version.
847
- void runLookup(lookup!.package.name, version, lookup!);
848
- }
849
-
850
- const manifest = lookup?.selected.manifest;
851
-
852
- async function add() {
853
- const token: number = openToken.current;
854
- setBusy(true);
855
- setError(null);
856
- const name: string = lookup!.package.name;
857
- const problem = await onAdd(name, selectedVersion, typeof manifest === "object" ? manifest.displayName : name);
858
- if (token === openToken.current) {
859
- setError(problem);
860
- setBusy(false);
861
- }
862
- }
863
-
864
- return (
865
- <Modal open={open} onClose={onClose} title="Add plugin">
866
- {error && <Alert>{error}</Alert>}
867
- <form onSubmit={find} className="flex gap-2 items-end mb-4">
868
- <label className="flex flex-col gap-1.5 text-sm flex-1">
869
- <span className="font-semibold">Package name</span>
870
- <input
871
- aria-label="Package name"
872
- className={INPUT_CLASS}
873
- value={name}
874
- placeholder="@rapidmx/activesync-plugin"
875
- onChange={(e) => {
876
- setName(e.target.value);
877
- invalidateLookup();
878
- setLookup(null);
879
- }}
880
- />
881
- </label>
882
- <Button type="submit" variant="secondary" className="!w-auto" loading={looking && !lookup} disabled={busy || looking}>
883
- Find
884
- </Button>
885
- </form>
886
- {lookup && (
887
- <div className="flex flex-col gap-3">
888
- {typeof manifest === "string" ? (
889
- <>
890
- <div className="text-sm font-semibold">{lookup.package.name}</div>
891
- <Alert>{manifest}</Alert>
892
- </>
893
- ) : (
894
- <div className="text-sm">
895
- <div className="font-semibold">{manifest?.displayName}</div>
896
- <div className="text-xs text-text-muted">{lookup.package.name}</div>
897
- {manifest?.description && <div className="text-text-muted">{manifest.description}</div>}
898
- </div>
899
- )}
900
- <label className="flex flex-col gap-1.5 text-sm">
901
- <span className="font-semibold">Version</span>
902
- <select aria-label="Version" className={INPUT_CLASS} value={selectedVersion} onChange={(e) => chooseVersion(e.target.value)}>
903
- {lookup.package.versions.map((version) => (
904
- <option key={version} value={version}>
905
- {version}
906
- {version === lookup.package.latest ? " (latest)" : ""}
907
- </option>
908
- ))}
909
- </select>
910
- </label>
911
- <div className="flex gap-2 justify-end">
912
- <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
913
- Cancel
914
- </Button>
915
- <Button
916
- type="button"
917
- className="!w-auto"
918
- loading={busy || looking}
919
- disabled={busy || looking || typeof manifest === "string"}
920
- onClick={() => void add()}
921
- >
922
- Add plugin
923
- </Button>
924
- </div>
925
- </div>
926
- )}
927
- </Modal>
928
- );
929
- }
930
-
931
- function ChangeVersionModal({
932
- plugin,
933
- onClose,
934
- onSave,
935
- }: {
936
- plugin: Plugin;
937
- onClose: () => void;
938
- /** Resolves why the version couldn't be changed, or `null`. */
939
- onSave: (packageVersion: string) => Promise<string | null>;
940
- }) {
941
- const [versions, setVersions] = useState<string[] | null>(null);
942
- const [latest, setLatest] = useState<string | undefined>();
943
- const [selected, setSelected] = useState(plugin.packageVersion);
944
- const [error, setError] = useState<string | null>(null);
945
- const [busy, setBusy] = useState(false);
946
-
947
- useEffect(() => {
948
- lookupPluginPackage(plugin.name)
949
- .then((found) => {
950
- setVersions(found.package.versions);
951
- setLatest(found.package.latest);
952
- })
953
- .catch((err) => setError(errorMessage(err, "Could not load the available versions.")));
954
- }, [plugin.name]);
955
-
956
- async function save() {
957
- setBusy(true);
958
- setError(null);
959
- const problem = await onSave(selected);
960
- if (problem) {
961
- setError(problem);
962
- setBusy(false);
963
- }
964
- }
965
-
966
- return (
967
- <Modal open onClose={onClose} title={`${plugin.manifest.displayName} version`}>
968
- {error && <Alert>{error}</Alert>}
969
- {versions === null ? (
970
- !error && <p className="text-sm text-text-muted">Loading&hellip;</p>
971
- ) : (
972
- <div className="flex flex-col gap-3">
973
- <label className="flex flex-col gap-1.5 text-sm">
974
- <span className="font-semibold">Version</span>
975
- <select aria-label="Version" className={INPUT_CLASS} value={selected} onChange={(e) => setSelected(e.target.value)}>
976
- {versions.map((version) => (
977
- <option key={version} value={version}>
978
- {version}
979
- {version === latest ? " (latest)" : ""}
980
- {version === plugin.packageVersion ? " (installed)" : ""}
981
- </option>
982
- ))}
983
- </select>
984
- </label>
985
- <div className="flex gap-2 justify-end">
986
- <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
987
- Cancel
988
- </Button>
989
- <Button
990
- type="button"
991
- className="!w-auto"
992
- loading={busy}
993
- disabled={busy || selected === plugin.packageVersion}
994
- onClick={() => void save()}
995
- >
996
- Save
997
- </Button>
998
- </div>
999
- </div>
1000
- )}
1001
- </Modal>
1002
- );
1003
- }
1004
-
1005
- /** Lists the plugins a change also installs or enables, and makes the change once confirmed. */
1006
- function ConfirmDependenciesModal({
1007
- change,
1008
- displayNameOf,
1009
- onClose,
1010
- onDone,
1011
- }: {
1012
- change: PendingChange;
1013
- displayNameOf: (name: string) => string;
1014
- onClose: () => void;
1015
- onDone: () => void;
1016
- }) {
1017
- const [error, setError] = useState<string | null>(null);
1018
- const [busy, setBusy] = useState(false);
1019
- const { plan } = change;
1020
-
1021
- async function proceed() {
1022
- setBusy(true);
1023
- setError(null);
1024
- try {
1025
- await change.apply(plan);
1026
- onDone();
1027
- } catch (err) {
1028
- setError(errorMessage(err, change.failure));
1029
- setBusy(false);
1030
- }
1031
- }
1032
-
1033
- return (
1034
- <Modal open onClose={onClose} title={`${change.displayName} requires other plugins`}>
1035
- {error && <Alert>{error}</Alert>}
1036
- <p className="text-sm mb-2">
1037
- {change.displayName} {plan.plugin.version} needs these plugins, so they&apos;ll be changed too:
1038
- </p>
1039
- <ul className="text-sm list-disc pl-5 mb-4">
1040
- {plan.install.map((dependency) => (
1041
- <li key={dependency.name}>
1042
- Install {dependency.manifest.displayName} {dependency.version}
1043
- </li>
1044
- ))}
1045
- {plan.enable.map((name) => (
1046
- <li key={name}>Enable {displayNameOf(name)}</li>
1047
- ))}
1048
- </ul>
1049
- <div className="flex gap-2 justify-end">
1050
- <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1051
- Cancel
1052
- </Button>
1053
- <Button type="button" className="!w-auto" loading={busy} disabled={busy} onClick={() => void proceed()}>
1054
- Continue
1055
- </Button>
1056
- </div>
1057
- </Modal>
1058
- );
1059
- }
1060
-
1061
- /** Whether a required select has no value to fall back on, so the form has to pick (and save) one. */
1062
- function needsSelection(definition: PluginSettingDefinition, saved: PluginSettingValue | undefined): boolean {
1063
- return (
1064
- definition.type === "select" &&
1065
- !!definition.required &&
1066
- saved === undefined &&
1067
- definition.default === undefined &&
1068
- (definition.options ?? []).length > 0
1069
- );
1070
- }
1071
-
1072
- /** A setting's current form value: its saved value, else its default - or, for a required select with neither, its
1073
- * first option. Kept as a string for text inputs. */
1074
- function initialValue(definition: PluginSettingDefinition, saved: PluginSettingValue | undefined): PluginSettingValue | "" {
1075
- if (needsSelection(definition, saved)) {
1076
- return definition.options![0].value;
1077
- }
1078
- const value = saved ?? definition.default;
1079
- if (definition.type === "boolean") {
1080
- return value === true;
1081
- }
1082
- return value === undefined ? "" : String(value);
1083
- }
1084
-
1085
- function SettingsModal({ plugin, onClose, onSaved }: { plugin: Plugin; onClose: () => void; onSaved: (plugin: Plugin) => void }) {
1086
- // Only opened from the Settings button, which is only shown for a plugin that declares settings.
1087
- const definitions: PluginSettingDefinition[] = plugin.manifest.settings!;
1088
- const initial = useRef(Object.fromEntries(definitions.map((d) => [d.key, initialValue(d, plugin.settings[d.key])])));
1089
- const [values, setValues] = useState<Record<string, PluginSettingValue | "">>(initial.current);
1090
- const [error, setError] = useState<string | null>(null);
1091
- const [busy, setBusy] = useState(false);
1092
-
1093
- async function save(e: FormEvent) {
1094
- e.preventDefault();
1095
- // The server replaces the whole settings object, so every setting is sent. One left alone is sent as it's saved
1096
- // - `null` when nothing is, so it keeps following the plugin's default rather than pinning the default shown.
1097
- // A required select with nothing to fall back on is sent as the form picked it.
1098
- const settings: Record<string, PluginSettingValue | null> = {};
1099
- let changed = false;
1100
- for (const definition of definitions) {
1101
- const key: string = definition.key;
1102
- const value = values[key];
1103
- if (value === initial.current[key] && !needsSelection(definition, plugin.settings[key])) {
1104
- settings[key] = plugin.settings[key] ?? null;
1105
- continue;
1106
- }
1107
- changed = true;
1108
- // A number input only ever reports a valid number or an empty string.
1109
- settings[key] = value === "" ? null : definition.type === "number" ? Number(value) : value;
1110
- }
1111
- if (!changed) {
1112
- onClose();
1113
- return;
1114
- }
1115
- setBusy(true);
1116
- setError(null);
1117
- try {
1118
- onSaved(await updatePlugin(plugin.uid, { version: plugin.version, settings }));
1119
- } catch (err) {
1120
- setError(errorMessage(err, "Could not save the settings."));
1121
- } finally {
1122
- setBusy(false);
1123
- }
1124
- }
1125
-
1126
- return (
1127
- <Modal open onClose={onClose} title={`${plugin.manifest.displayName} settings`}>
1128
- {error && <Alert>{error}</Alert>}
1129
- <form onSubmit={save} className="flex flex-col gap-4">
1130
- {definitions.map((definition) => (
1131
- <SettingField
1132
- key={definition.key}
1133
- definition={definition}
1134
- value={values[definition.key]}
1135
- onChange={(value) => setValues((prev) => ({ ...prev, [definition.key]: value }))}
1136
- />
1137
- ))}
1138
- <p className="text-xs text-text-muted">Saving restarts the servers one at a time to apply the new settings.</p>
1139
- <div className="flex gap-2 justify-end">
1140
- <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1141
- Cancel
1142
- </Button>
1143
- <Button type="submit" className="!w-auto" loading={busy} disabled={busy}>
1144
- Save
1145
- </Button>
1146
- </div>
1147
- </form>
1148
- </Modal>
1149
- );
1150
- }
1151
-
1152
- function SettingField({
1153
- definition,
1154
- value,
1155
- onChange,
1156
- }: {
1157
- definition: PluginSettingDefinition;
1158
- value: PluginSettingValue | "";
1159
- onChange: (value: PluginSettingValue | "") => void;
1160
- }) {
1161
- const help = definition.help && <span className="text-xs text-text-muted">{definition.help}</span>;
1162
- if (definition.type === "boolean") {
1163
- return (
1164
- <label className="flex flex-col gap-1 text-sm">
1165
- <span className="inline-flex items-center gap-2 font-semibold">
1166
- <input type="checkbox" checked={value === true} onChange={(e) => onChange(e.target.checked)} />
1167
- {definition.label}
1168
- </span>
1169
- {help}
1170
- </label>
1171
- );
1172
- }
1173
- return (
1174
- <label className="flex flex-col gap-1.5 text-sm">
1175
- <span className="font-semibold">{definition.label}</span>
1176
- {definition.type === "select" ? (
1177
- <select aria-label={definition.label} className={INPUT_CLASS} value={String(value)} onChange={(e) => onChange(e.target.value)}>
1178
- {!definition.required && <option value="">Default</option>}
1179
- {(definition.options ?? []).map((option) => (
1180
- <option key={option.value} value={option.value}>
1181
- {option.label}
1182
- </option>
1183
- ))}
1184
- </select>
1185
- ) : (
1186
- <input
1187
- aria-label={definition.label}
1188
- className={INPUT_CLASS}
1189
- type={definition.type === "number" ? "number" : "text"}
1190
- min={definition.min}
1191
- max={definition.max}
1192
- required={definition.required}
1193
- value={String(value)}
1194
- onChange={(e) => onChange(e.target.value)}
1195
- />
1196
- )}
1197
- {help}
1198
- </label>
1199
- );
1200
- }
1201
-
1202
- function RemoveModal({ plugin, onClose, onRemoved }: { plugin: Plugin; onClose: () => void; onRemoved: () => void }) {
1203
- const [error, setError] = useState<string | null>(null);
1204
- const [busy, setBusy] = useState(false);
1205
-
1206
- async function remove() {
1207
- setBusy(true);
1208
- setError(null);
1209
- try {
1210
- await removePlugin(plugin.uid);
1211
- onRemoved();
1212
- } catch (err) {
1213
- setError(errorMessage(err, "Could not uninstall the plugin."));
1214
- setBusy(false);
1215
- }
1216
- }
1217
-
1218
- return (
1219
- <Modal open onClose={onClose} title={`Uninstall ${plugin.manifest.displayName}?`}>
1220
- {error && <Alert>{error}</Alert>}
1221
- <p className="text-sm mb-4">
1222
- The servers stop running this plugin after they restart. Data it stored stays in the database, and adding
1223
- the plugin again brings it back.
1224
- </p>
1225
- <div className="flex gap-2 justify-end">
1226
- <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1227
- Cancel
1228
- </Button>
1229
- <Button type="button" className="!w-auto" loading={busy} disabled={busy} onClick={() => void remove()}>
1230
- Uninstall
1231
- </Button>
1232
- </div>
1233
- </Modal>
1234
- );
1235
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { FormEvent, useCallback, useEffect, useRef, useState } from "react";
6
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
+ import {
8
+ addPlugin,
9
+ expectedPlanOf,
10
+ getPluginStatus,
11
+ getPluginUpdates,
12
+ listPluginNamespaces,
13
+ listPlugins,
14
+ lookupPluginPackage,
15
+ planPluginChange,
16
+ Plugin,
17
+ PluginChangePlan,
18
+ PluginInstanceStatus,
19
+ PluginNamespace,
20
+ PluginRegistryLookup,
21
+ PluginSearchResult,
22
+ PluginSettingDefinition,
23
+ PluginSettingValue,
24
+ PluginStatus,
25
+ PluginUpdateInfo,
26
+ removePlugin,
27
+ searchPlugins,
28
+ updatePlugin,
29
+ } from "@rapidmx/react-shared/admin/pluginsApi.js";
30
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
31
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
32
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
33
+
34
+ const INPUT_CLASS =
35
+ "w-full text-sm py-2.5 px-3 border border-border rounded-sm bg-surface text-text focus:outline-none focus:border-primary";
36
+
37
+ /** How often status is refreshed while server copies are still applying a change. */
38
+ const PENDING_POLL_MS = 5000;
39
+
40
+ /** How long status keeps being polled after a saved change, since servers may not have noticed it yet. */
41
+ const AFTER_CHANGE_POLL_MS = 2 * 60 * 1000;
42
+
43
+ /** The longest wait between retries while no status has ever been read. */
44
+ const MAX_STATUS_RETRY_MS = 60 * 1000;
45
+
46
+ function errorMessage(err: unknown, fallback: string): string {
47
+ return err instanceof ApiRequestError ? err.message : fallback;
48
+ }
49
+
50
+ /** Runs `action`, resolving why it failed, or `null`. */
51
+ async function attempt(action: () => Promise<void>, failure: string): Promise<string | null> {
52
+ try {
53
+ await action();
54
+ return null;
55
+ } catch (err) {
56
+ return errorMessage(err, failure);
57
+ }
58
+ }
59
+
60
+ /** A change waiting for the administrator to confirm the other plugins it also installs or enables. */
61
+ interface PendingChange {
62
+ displayName: string;
63
+ plan: PluginChangePlan;
64
+ apply: (plan: PluginChangePlan) => Promise<void>;
65
+ failure: string;
66
+ /** The installed plugin being changed, which stays busy while the change waits for confirmation. */
67
+ uid?: string;
68
+ }
69
+
70
+ /** Classes for a plugin table's header and body cells. */
71
+ const TH_CLASS = "text-left text-xs uppercase tracking-wide text-text-muted py-2 px-2.5 border-b border-border";
72
+ const TD_CLASS = "py-3 px-2.5 border-b border-border align-top";
73
+
74
+ /**
75
+ * The installed plugins table stacks each row on narrow screens - name and description, then version and status side
76
+ * by side, then the actions - so the actions aren't scrolled off to the side. The explicit roles keep it a table for
77
+ * assistive technology while it isn't displayed as one.
78
+ */
79
+ const INSTALLED_ROW_CLASS = "flex flex-wrap border-b border-border lg:table-row lg:border-b-0";
80
+ const INSTALLED_TD_CLASS = "block px-2.5 align-top lg:table-cell lg:pt-3 lg:pb-3 lg:border-b lg:border-border";
81
+
82
+ /** The small pill badge admin tables use for a state. */
83
+ const BADGE_CLASS = "inline-block text-xs font-bold uppercase tracking-wide py-0.5 px-2 rounded-pill";
84
+
85
+ export interface PluginsManagerProps {
86
+ /**
87
+ * Set when shown inside another page that already has its own heading and introduction (the setup wizard): the
88
+ * page heading and introduction are left out, and the section headings sit one level lower.
89
+ */
90
+ embedded?: boolean;
91
+ }
92
+
93
+ /** Installed plugins with their rollout status, and every plugin action - shared by the Plugins page and the
94
+ * setup wizard. */
95
+ export default function PluginsManager({ embedded = false }: PluginsManagerProps = {}) {
96
+ const [plugins, setPlugins] = useState<Plugin[]>([]);
97
+ const [status, setStatus] = useState<PluginStatus | null>(null);
98
+ /** Set when the last status refresh failed, so what's shown may be out of date. */
99
+ const [statusStale, setStatusStale] = useState(false);
100
+ /** When polling started by a saved change stops (epoch ms), or 0 when there's none. */
101
+ const [pollUntil, setPollUntil] = useState(0);
102
+ const [updates, setUpdates] = useState<Map<string, PluginUpdateInfo>>(new Map());
103
+ const [loading, setLoading] = useState(true);
104
+ const [error, setError] = useState<string | null>(null);
105
+ /** The installed plugin whose enable just failed, offered a retry next to `error`. */
106
+ const [retryEnableUid, setRetryEnableUid] = useState<string | null>(null);
107
+ const [adding, setAdding] = useState(false);
108
+ const [upgrading, setUpgrading] = useState<Plugin | null>(null);
109
+ const [configuring, setConfiguring] = useState<Plugin | null>(null);
110
+ const [removing, setRemoving] = useState<Plugin | null>(null);
111
+ const [confirming, setConfirming] = useState<PendingChange | null>(null);
112
+ /** Installed plugins with an action under way. */
113
+ const [busyUids, setBusyUids] = useState<ReadonlySet<string>>(new Set());
114
+ /** Set when re-reading the list after a change failed, so rows may not show what that change also did. */
115
+ const [listStale, setListStale] = useState(false);
116
+ /** How many times status has been retried while none has ever been read. */
117
+ const [statusRetries, setStatusRetries] = useState(0);
118
+ const statusRequest = useRef<Promise<void> | null>(null);
119
+
120
+ const setBusy = (uid: string, busy: boolean) =>
121
+ setBusyUids((prev) => {
122
+ const next = new Set(prev);
123
+ if (busy) {
124
+ next.add(uid);
125
+ } else {
126
+ next.delete(uid);
127
+ }
128
+ return next;
129
+ });
130
+
131
+ const refreshStatus = useCallback(() => {
132
+ // One read at a time: a poll that comes due while a slow read is still running shares it.
133
+ statusRequest.current ??= getPluginStatus()
134
+ .then((next) => {
135
+ setStatus(next);
136
+ setStatusStale(false);
137
+ })
138
+ // Status is advisory - a failure to read it shouldn't hide the plugin list, or lose the last status read.
139
+ .catch(() => setStatusStale(true))
140
+ .finally(() => {
141
+ statusRequest.current = null;
142
+ });
143
+ return statusRequest.current;
144
+ }, []);
145
+
146
+ const refreshUpdates = useCallback(() => {
147
+ // Also advisory: a registry that can't be reached just means no update badges.
148
+ return getPluginUpdates()
149
+ .then((list) => setUpdates(new Map(list.map((info) => [info.uid, info]))))
150
+ .catch(() => setUpdates(new Map()));
151
+ }, []);
152
+
153
+ /** Re-reads the list, for changes that also installed or enabled other plugins. */
154
+ const reload = useCallback(() => {
155
+ return listPlugins()
156
+ .then((list) => {
157
+ setPlugins(list);
158
+ setListStale(false);
159
+ })
160
+ .catch(() => setListStale(true));
161
+ }, []);
162
+
163
+ useEffect(() => {
164
+ Promise.all([listPlugins(), refreshStatus()])
165
+ .then(([list]) => {
166
+ setPlugins(list);
167
+ void refreshUpdates();
168
+ })
169
+ .catch((err) => setError(errorMessage(err, "Could not load plugins.")))
170
+ .finally(() => setLoading(false));
171
+ }, [refreshStatus, refreshUpdates]);
172
+
173
+ const pending: boolean = !!status && status.instances.some((instance) => instance.hash !== status.hash);
174
+ useEffect(() => {
175
+ if (!pending && pollUntil === 0) {
176
+ return;
177
+ }
178
+ const timer = setInterval(() => void refreshStatus(), PENDING_POLL_MS);
179
+ // Polling for a saved change ends after a while; a rollout that's under way keeps it going.
180
+ const stop = pollUntil > 0 ? setTimeout(() => setPollUntil(0), Math.max(0, pollUntil - Date.now())) : undefined;
181
+ return () => {
182
+ clearInterval(timer);
183
+ clearTimeout(stop);
184
+ };
185
+ }, [pending, pollUntil, refreshStatus]);
186
+
187
+ // With no status read at all there's nothing pending to poll for, so keep retrying - less often each time.
188
+ const neverRead: boolean = !status && statusStale;
189
+ useEffect(() => {
190
+ if (!neverRead) {
191
+ return;
192
+ }
193
+ const timer = setTimeout(
194
+ () => void refreshStatus().then(() => setStatusRetries((n) => n + 1)),
195
+ Math.min(PENDING_POLL_MS * 2 ** statusRetries, MAX_STATUS_RETRY_MS),
196
+ );
197
+ return () => clearTimeout(timer);
198
+ }, [neverRead, statusRetries, refreshStatus]);
199
+
200
+ /** Re-reads status, and keeps doing so for a while, since saving starts a rollout servers pick up shortly. */
201
+ function watchRollout() {
202
+ setPollUntil(Date.now() + AFTER_CHANGE_POLL_MS);
203
+ void refreshStatus();
204
+ }
205
+
206
+ /** Applies saved changes locally and re-reads status and updates, since saving starts a rollout. */
207
+ function applied(...changed: Plugin[]) {
208
+ setPlugins((prev) => {
209
+ let next = prev;
210
+ for (const updated of changed) {
211
+ const exists = next.some((plugin) => plugin.uid === updated.uid);
212
+ next = exists ? next.map((plugin) => (plugin.uid === updated.uid ? updated : plugin)) : [...next, updated];
213
+ }
214
+ return [...next].sort((a, b) => a.name.localeCompare(b.name));
215
+ });
216
+ watchRollout();
217
+ void refreshUpdates();
218
+ }
219
+
220
+ /** Runs an action on an installed plugin's row, which is busy meanwhile, and shows why it failed. */
221
+ async function onRow(plugin: Plugin, action: () => Promise<string | null>) {
222
+ setBusy(plugin.uid, true);
223
+ setError(null);
224
+ setRetryEnableUid(null);
225
+ const problem = await action();
226
+ if (problem) {
227
+ setError(problem);
228
+ }
229
+ // A change waiting for confirmation keeps the row busy by itself, until the confirmation closes.
230
+ setBusy(plugin.uid, false);
231
+ }
232
+
233
+ function toggle(plugin: Plugin) {
234
+ const displayName: string = plugin.manifest.displayName;
235
+ if (plugin.enabled) {
236
+ return onRow(plugin, () =>
237
+ attempt(async () => applied(await updatePlugin(plugin.uid, { version: plugin.version, enabled: false })), `Could not disable ${displayName}.`),
238
+ );
239
+ }
240
+ // Enabling a plugin also installs or enables the plugins it requires, so it's previewed like any other change.
241
+ // The installed version is planned from its stored manifest, so this doesn't need the registry. A preview that
242
+ // fails is never skipped - enabling without one could install or enable other plugins the administrator never
243
+ // saw - so the failure is shown with a retry instead.
244
+ return onRow(plugin, async () => {
245
+ const problem = await planned(
246
+ plugin.name,
247
+ plugin.packageVersion,
248
+ displayName,
249
+ async (plan) => {
250
+ applied(await updatePlugin(plugin.uid, { version: plugin.version, enabled: true, expectedPlan: expectedPlanOf(plan) }));
251
+ if (plan.install.length > 0 || plan.enable.length > 0) {
252
+ void reload();
253
+ }
254
+ },
255
+ `Could not enable ${displayName}.`,
256
+ { uid: plugin.uid },
257
+ );
258
+ if (problem) {
259
+ setRetryEnableUid(plugin.uid);
260
+ }
261
+ return problem;
262
+ });
263
+ }
264
+
265
+ /**
266
+ * Checks what installing or changing a plugin also takes before doing it. Resolves why it can't be done, or `null`
267
+ * once it's done - or, when it also installs or enables other plugins, once they're shown for confirmation.
268
+ */
269
+ async function planned(
270
+ name: string,
271
+ packageVersion: string,
272
+ displayName: string,
273
+ apply: (plan: PluginChangePlan) => Promise<void>,
274
+ failure: string,
275
+ options: { uid?: string } = {},
276
+ ): Promise<string | null> {
277
+ let plan: PluginChangePlan;
278
+ try {
279
+ plan = await planPluginChange(name, packageVersion);
280
+ } catch (err) {
281
+ return errorMessage(err, failure);
282
+ }
283
+ if (plan.conflicts.length > 0) {
284
+ return `${displayName} ${plan.plugin.version} can't be installed. ${plan.conflicts.join(" ")}`;
285
+ }
286
+ if (plan.install.length > 0 || plan.enable.length > 0) {
287
+ setConfirming({ displayName, plan, apply, failure, uid: options.uid });
288
+ return null;
289
+ }
290
+ return attempt(() => apply(plan), failure);
291
+ }
292
+
293
+ function install(name: string, packageVersion: string, displayName: string) {
294
+ return planned(
295
+ name,
296
+ packageVersion,
297
+ displayName,
298
+ async (plan) => {
299
+ const result = await addPlugin(name, packageVersion, expectedPlanOf(plan));
300
+ applied(...result.dependencies, result.plugin);
301
+ },
302
+ `Could not install ${displayName}.`,
303
+ );
304
+ }
305
+
306
+ function changeVersion(plugin: Plugin, packageVersion: string) {
307
+ const failure = `Could not upgrade ${plugin.manifest.displayName}.`;
308
+ if (!plugin.enabled) {
309
+ // A disabled plugin stays disabled, so nothing it requires is installed or enabled - there's nothing to preview.
310
+ return attempt(async () => applied(await updatePlugin(plugin.uid, { version: plugin.version, packageVersion })), failure);
311
+ }
312
+ return planned(
313
+ plugin.name,
314
+ packageVersion,
315
+ plugin.manifest.displayName,
316
+ async (plan) => {
317
+ applied(await updatePlugin(plugin.uid, { version: plugin.version, packageVersion, expectedPlan: expectedPlanOf(plan) }));
318
+ if (plan.install.length > 0 || plan.enable.length > 0) {
319
+ void reload();
320
+ }
321
+ },
322
+ failure,
323
+ { uid: plugin.uid },
324
+ );
325
+ }
326
+
327
+ function upgrade(plugin: Plugin, packageVersion: string) {
328
+ return onRow(plugin, () => changeVersion(plugin, packageVersion));
329
+ }
330
+
331
+ // Retried against the plugin as it's listed now (a newer version, or already enabled elsewhere, hides the retry).
332
+ const retryEnable: Plugin | undefined = plugins.find((plugin) => plugin.uid === retryEnableUid && !plugin.enabled);
333
+
334
+ const displayNameOf = (name: string): string => plugins.find((plugin) => plugin.name === name)?.manifest.displayName ?? name;
335
+
336
+ const SectionHeading = embedded ? "h3" : "h2";
337
+ const addButton = (
338
+ <Button type="button" variant="secondary" className="!w-auto shrink-0" onClick={() => setAdding(true)}>
339
+ Add by name
340
+ </Button>
341
+ );
342
+
343
+ return (
344
+ <>
345
+ {embedded ? (
346
+ <p className="text-sm text-text-muted mb-5 max-w-3xl">
347
+ Changes are applied by restarting the servers one at a time, so mail keeps flowing. Plugins run
348
+ with full access to the server, so only add ones you trust.
349
+ </p>
350
+ ) : (
351
+ <>
352
+ <div className="flex items-center justify-between gap-4 mb-2">
353
+ <h1 className="text-xl font-bold uppercase tracking-wide">Plugins</h1>
354
+ {addButton}
355
+ </div>
356
+ <p className="text-sm text-text-muted mb-6 max-w-3xl">
357
+ Plugins add protocols and features to every server. Changes are applied by restarting the
358
+ servers one at a time, so mail keeps flowing. Plugins run with full access to the server, so
359
+ only add ones you trust.
360
+ </p>
361
+ </>
362
+ )}
363
+
364
+ {error && (
365
+ <Alert>
366
+ {error}
367
+ {retryEnable && (
368
+ <>
369
+ {" "}
370
+ <Button
371
+ type="button"
372
+ variant="text"
373
+ className="!w-auto !p-0"
374
+ onClick={() => void toggle(retryEnable)}
375
+ >
376
+ Try again
377
+ </Button>
378
+ </>
379
+ )}
380
+ </Alert>
381
+ )}
382
+ <RolloutBanner status={status} />
383
+ {statusStale && status && (
384
+ <p className="mb-4 text-xs text-text-muted">Couldn&apos;t refresh server status. Showing the last status reported.</p>
385
+ )}
386
+ {listStale && (
387
+ <p className="mb-4 text-xs text-text-muted">
388
+ Couldn&apos;t re-read the plugin list, so it may be out of date.{" "}
389
+ <Button type="button" variant="text" className="!w-auto !p-0 !text-xs" onClick={() => void reload()}>
390
+ Retry
391
+ </Button>
392
+ </p>
393
+ )}
394
+
395
+ <div className="flex items-center justify-between gap-4 mb-2">
396
+ <SectionHeading className="text-sm font-bold uppercase tracking-wide">Installed plugins</SectionHeading>
397
+ {embedded && addButton}
398
+ </div>
399
+ {loading ? (
400
+ <p className="text-sm text-text-muted">Loading&hellip;</p>
401
+ ) : plugins.length === 0 ? (
402
+ <p className="text-sm text-text-muted">No plugins installed.</p>
403
+ ) : (
404
+ <div className="overflow-x-auto">
405
+ <table role="table" className="w-full text-sm border-collapse block lg:table">
406
+ <thead role="rowgroup" className="hidden lg:table-header-group">
407
+ <tr role="row">
408
+ <th role="columnheader" className={TH_CLASS}>
409
+ Plugin
410
+ </th>
411
+ <th role="columnheader" className={TH_CLASS}>
412
+ Version
413
+ </th>
414
+ <th role="columnheader" className={TH_CLASS}>
415
+ Status
416
+ </th>
417
+ <th role="columnheader" className={TH_CLASS}>
418
+ <span className="sr-only">Actions</span>
419
+ </th>
420
+ </tr>
421
+ </thead>
422
+ <tbody role="rowgroup" className="block lg:table-row-group">
423
+ {plugins.map((plugin) => {
424
+ const update: PluginUpdateInfo | undefined = updates.get(plugin.uid);
425
+ const latest: string | undefined = update?.updateAvailable ? update.latestVersion : undefined;
426
+ const busy: boolean = busyUids.has(plugin.uid) || confirming?.uid === plugin.uid;
427
+ const requires: string[] = Object.keys(plugin.manifest.requires ?? {}).map(displayNameOf);
428
+ const requiredBy: string[] = plugins
429
+ .filter((other) => other.uid !== plugin.uid && other.manifest.requires?.[plugin.name] !== undefined)
430
+ .map((other) => other.manifest.displayName);
431
+ return (
432
+ <tr key={plugin.uid} role="row" className={INSTALLED_ROW_CLASS}>
433
+ <td role="cell" className={`${INSTALLED_TD_CLASS} basis-full pt-3 pb-2`}>
434
+ <div className="font-semibold">{plugin.manifest.displayName}</div>
435
+ <div className="text-xs text-text-muted">{plugin.name}</div>
436
+ {plugin.manifest.description && (
437
+ <div className="text-xs text-text-muted mt-1 max-w-md">{plugin.manifest.description}</div>
438
+ )}
439
+ {requires.length > 0 && <div className="text-xs text-text-muted mt-1">Requires: {requires.join(", ")}</div>}
440
+ {requiredBy.length > 0 && (
441
+ <div className="text-xs text-text-muted mt-1">Required by: {requiredBy.join(", ")}</div>
442
+ )}
443
+ </td>
444
+ <td role="cell" className={`${INSTALLED_TD_CLASS} pt-1 pb-1 whitespace-nowrap`}>
445
+ <div>{plugin.packageVersion}</div>
446
+ {latest && <div className="mt-1 text-xs font-semibold text-primary-dark">Update available: {latest}</div>}
447
+ </td>
448
+ <td role="cell" className={`${INSTALLED_TD_CLASS} pt-1 pb-1`}>
449
+ <PluginStatusCell plugin={plugin} status={status} />
450
+ </td>
451
+ <td role="cell" className={`${INSTALLED_TD_CLASS} basis-full pt-2 pb-3`}>
452
+ <div className="flex flex-col items-start gap-1.5 lg:items-end lg:min-w-[11rem]">
453
+ <div className="flex flex-wrap gap-2 lg:justify-end">
454
+ {latest && (
455
+ <Button
456
+ type="button"
457
+ variant="secondary"
458
+ className="!w-auto"
459
+ aria-label={`Upgrade ${plugin.manifest.displayName} to ${latest}`}
460
+ disabled={busy}
461
+ onClick={() => void upgrade(plugin, latest)}
462
+ >
463
+ Upgrade
464
+ </Button>
465
+ )}
466
+ {(plugin.manifest.settings ?? []).length > 0 && (
467
+ <Button variant="secondary" type="button" className="!w-auto" onClick={() => setConfiguring(plugin)}>
468
+ Settings
469
+ </Button>
470
+ )}
471
+ <Button
472
+ variant={plugin.enabled ? "secondary" : "primary"}
473
+ type="button"
474
+ className="!w-auto min-w-[5.5rem]"
475
+ aria-label={`${plugin.enabled ? "Disable" : "Enable"} ${plugin.manifest.displayName}`}
476
+ disabled={busy}
477
+ onClick={() => void toggle(plugin)}
478
+ >
479
+ {plugin.enabled ? "Disable" : "Enable"}
480
+ </Button>
481
+ </div>
482
+ <div className="flex flex-wrap gap-x-4 lg:justify-end">
483
+ <Button variant="text" type="button" onClick={() => setUpgrading(plugin)}>
484
+ Change version
485
+ </Button>
486
+ <Button variant="text" type="button" onClick={() => setRemoving(plugin)}>
487
+ Uninstall
488
+ </Button>
489
+ </div>
490
+ </div>
491
+ </td>
492
+ </tr>
493
+ );
494
+ })}
495
+ </tbody>
496
+ </table>
497
+ </div>
498
+ )}
499
+
500
+ <PluginBrowser
501
+ headingLevel={SectionHeading}
502
+ plugins={plugins}
503
+ onInstall={(result) => install(result.name, result.version, result.name)}
504
+ // The browser only offers an upgrade for a result it matched to one of these same `plugins`.
505
+ onUpgrade={(uid, packageVersion) => upgrade(plugins.find((p) => p.uid === uid)!, packageVersion)}
506
+ />
507
+
508
+ <AddPluginModal
509
+ open={adding}
510
+ onClose={() => setAdding(false)}
511
+ onAdd={async (name, packageVersion, displayName) => {
512
+ const problem = await install(name, packageVersion, displayName);
513
+ if (!problem) {
514
+ setAdding(false);
515
+ }
516
+ return problem;
517
+ }}
518
+ />
519
+ {upgrading && (
520
+ <ChangeVersionModal
521
+ plugin={upgrading}
522
+ onClose={() => setUpgrading(null)}
523
+ onSave={async (packageVersion) => {
524
+ const problem = await changeVersion(upgrading, packageVersion);
525
+ if (!problem) {
526
+ setUpgrading(null);
527
+ }
528
+ return problem;
529
+ }}
530
+ />
531
+ )}
532
+ {confirming && (
533
+ <ConfirmDependenciesModal
534
+ change={confirming}
535
+ displayNameOf={displayNameOf}
536
+ onClose={() => setConfirming(null)}
537
+ onDone={() => setConfirming(null)}
538
+ />
539
+ )}
540
+ {configuring && (
541
+ <SettingsModal
542
+ plugin={configuring}
543
+ onClose={() => setConfiguring(null)}
544
+ onSaved={(plugin) => {
545
+ setConfiguring(null);
546
+ applied(plugin);
547
+ }}
548
+ />
549
+ )}
550
+ {removing && (
551
+ <RemoveModal
552
+ plugin={removing}
553
+ onClose={() => setRemoving(null)}
554
+ onRemoved={() => {
555
+ const uid = removing.uid;
556
+ setRemoving(null);
557
+ setPlugins((prev) => prev.filter((plugin) => plugin.uid !== uid));
558
+ watchRollout();
559
+ }}
560
+ />
561
+ )}
562
+ </>
563
+ );
564
+ }
565
+
566
+ const ALL_NAMESPACES = "";
567
+
568
+ /** Searches the configured namespaces' registries for plugin packages, with install and upgrade actions. */
569
+ function PluginBrowser({
570
+ headingLevel: Heading,
571
+ plugins,
572
+ onInstall,
573
+ onUpgrade,
574
+ }: {
575
+ headingLevel: "h2" | "h3";
576
+ plugins: Plugin[];
577
+ /** Resolves why the plugin couldn't be installed, or `null`. */
578
+ onInstall: (result: PluginSearchResult) => Promise<string | null>;
579
+ onUpgrade: (uid: string, packageVersion: string) => Promise<void>;
580
+ }) {
581
+ const [namespaces, setNamespaces] = useState<PluginNamespace[]>([]);
582
+ const [namespace, setNamespace] = useState(ALL_NAMESPACES);
583
+ const [results, setResults] = useState<PluginSearchResult[] | null>(null);
584
+ const [searching, setSearching] = useState(false);
585
+ const [busyName, setBusyName] = useState<string | null>(null);
586
+ const [error, setError] = useState<string | null>(null);
587
+
588
+ useEffect(() => {
589
+ listPluginNamespaces()
590
+ .then(setNamespaces)
591
+ .catch(() => setNamespaces([]));
592
+ }, []);
593
+
594
+ async function search(e: FormEvent) {
595
+ e.preventDefault();
596
+ setSearching(true);
597
+ setError(null);
598
+ try {
599
+ setResults(await searchPlugins(namespace || undefined));
600
+ } catch (err) {
601
+ setResults(null);
602
+ setError(errorMessage(err, "Could not search for plugins."));
603
+ } finally {
604
+ setSearching(false);
605
+ }
606
+ }
607
+
608
+ // Keep results in step with installs and upgrades made anywhere on the page.
609
+ const rows: PluginSearchResult[] = (results ?? []).map((result) => {
610
+ const installed: Plugin | undefined = plugins.find((plugin) => plugin.name === result.name);
611
+ return {
612
+ ...result,
613
+ installedUid: installed?.uid,
614
+ installedVersion: installed?.packageVersion,
615
+ updateAvailable: !!installed && installed.packageVersion !== result.version && result.updateAvailable,
616
+ };
617
+ });
618
+
619
+ async function install(result: PluginSearchResult) {
620
+ setBusyName(result.name);
621
+ setError(null);
622
+ setError(await onInstall(result));
623
+ setBusyName(null);
624
+ }
625
+
626
+ async function upgrade(result: PluginSearchResult) {
627
+ setBusyName(result.name);
628
+ try {
629
+ await onUpgrade(result.installedUid!, result.version);
630
+ } finally {
631
+ setBusyName(null);
632
+ }
633
+ }
634
+
635
+ return (
636
+ <section aria-labelledby="plugin-browser-title" className="mt-8">
637
+ <Heading id="plugin-browser-title" className="text-sm font-bold uppercase tracking-wide mb-2">
638
+ Find plugins
639
+ </Heading>
640
+ <form onSubmit={(e) => void search(e)} className="flex flex-wrap gap-2 items-end mb-3">
641
+ <label className="flex flex-col gap-1.5 text-sm">
642
+ <span className="font-semibold">Namespace</span>
643
+ <select aria-label="Namespace" className={INPUT_CLASS} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
644
+ <option value={ALL_NAMESPACES}>All namespaces</option>
645
+ {namespaces.map((ns) => (
646
+ <option key={ns.name} value={ns.name}>
647
+ {ns.name}
648
+ </option>
649
+ ))}
650
+ </select>
651
+ </label>
652
+ <Button type="submit" className="!w-auto" loading={searching} disabled={searching}>
653
+ Search
654
+ </Button>
655
+ </form>
656
+ {error && <Alert>{error}</Alert>}
657
+ {results !== null &&
658
+ (rows.length === 0 ? (
659
+ <p className="text-sm text-text-muted">No plugins found.</p>
660
+ ) : (
661
+ <div className="overflow-x-auto">
662
+ <table className="w-full text-sm border-collapse">
663
+ <thead>
664
+ <tr>
665
+ <th className={TH_CLASS}>Package</th>
666
+ <th className={TH_CLASS}>Latest version</th>
667
+ <th className={TH_CLASS}>Status</th>
668
+ <th className={TH_CLASS}>
669
+ <span className="sr-only">Actions</span>
670
+ </th>
671
+ </tr>
672
+ </thead>
673
+ <tbody>
674
+ {rows.map((result) => (
675
+ <tr key={result.name}>
676
+ <td className={TD_CLASS}>
677
+ <div className="font-semibold">{result.name}</div>
678
+ {result.description && <div className="text-xs text-text-muted max-w-md">{result.description}</div>}
679
+ </td>
680
+ <td className={TD_CLASS}>{result.version}</td>
681
+ <td className={`${TD_CLASS} text-text-muted`}>
682
+ {result.updateAvailable
683
+ ? `Installed ${result.installedVersion} - update available`
684
+ : result.installedUid
685
+ ? `Installed ${result.installedVersion}`
686
+ : result.allowed
687
+ ? "Not installed"
688
+ : "Not allowed on this server"}
689
+ </td>
690
+ <td className={`${TD_CLASS} text-right`}>
691
+ {result.updateAvailable ? (
692
+ <Button
693
+ type="button"
694
+ variant="secondary"
695
+ className="!w-auto"
696
+ aria-label={`Upgrade ${result.name} to ${result.version}`}
697
+ disabled={busyName === result.name}
698
+ onClick={() => void upgrade(result)}
699
+ >
700
+ Upgrade
701
+ </Button>
702
+ ) : (
703
+ !result.installedUid &&
704
+ result.allowed && (
705
+ <Button
706
+ type="button"
707
+ className="!w-auto"
708
+ aria-label={`Install ${result.name}`}
709
+ loading={busyName === result.name}
710
+ disabled={busyName === result.name}
711
+ onClick={() => void install(result)}
712
+ >
713
+ Install
714
+ </Button>
715
+ )
716
+ )}
717
+ </td>
718
+ </tr>
719
+ ))}
720
+ </tbody>
721
+ </table>
722
+ </div>
723
+ ))}
724
+ </section>
725
+ );
726
+ }
727
+
728
+ /** Name a server reports an error under when it isn't about any single plugin (e.g. the plugin set as a whole failed). */
729
+ const SERVER_WIDE_ERROR_NAME = "*";
730
+
731
+ /**
732
+ * Shown while any server copy hasn't applied the saved plugin set yet, when one is in safe mode, or when one reports a
733
+ * server-wide plugin error - those match no plugin row, so without this they'd never be shown.
734
+ */
735
+ function RolloutBanner({ status }: { status: PluginStatus | null }) {
736
+ if (!status || status.instances.length === 0) {
737
+ return null;
738
+ }
739
+ const behind = status.instances.filter((instance) => instance.hash !== status.hash).length;
740
+ const safeMode = status.instances.filter((instance) => instance.safeMode);
741
+ const serverWideErrors = status.instances.flatMap((instance) =>
742
+ instance.errors
743
+ .filter((entry) => entry.name === SERVER_WIDE_ERROR_NAME)
744
+ .map((entry) => `${instance.instance}: ${entry.message}`),
745
+ );
746
+ return (
747
+ <>
748
+ {serverWideErrors.length > 0 && (
749
+ <Alert>
750
+ Plugins couldn&rsquo;t be loaded:
751
+ <ul className="list-disc pl-5 mt-1">
752
+ {serverWideErrors.map((message) => (
753
+ <li key={message} className="break-words">
754
+ {message}
755
+ </li>
756
+ ))}
757
+ </ul>
758
+ </Alert>
759
+ )}
760
+ {behind > 0 && (
761
+ <p role="status" className="mb-4 text-sm py-2 px-3 rounded-sm bg-surface-alt text-text">
762
+ Applying changes: {status.instances.length - behind} of {status.instances.length}{" "}
763
+ {status.instances.length === 1 ? "server" : "servers"} updated. Servers restart one at a time.
764
+ </p>
765
+ )}
766
+ {safeMode.length > 0 && (
767
+ <Alert>
768
+ {safeMode.map((instance) => instance.instance).join(", ")} started without any plugins because recent
769
+ starts failed. Fix or disable the failing plugin, and the server will pick up the change.
770
+ </Alert>
771
+ )}
772
+ </>
773
+ );
774
+ }
775
+
776
+ /** A plugin's enabled state and, for an enabled one, how many servers have loaded it and what went wrong. */
777
+ function PluginStatusCell({ plugin, status }: { plugin: Plugin; status: PluginStatus | null }) {
778
+ if (!plugin.enabled) {
779
+ return <span className={`${BADGE_CLASS} bg-surface-alt text-text-muted`}>Disabled</span>;
780
+ }
781
+ return (
782
+ <div className="flex flex-col items-start gap-1">
783
+ <span className={`${BADGE_CLASS} bg-success text-white`}>Enabled</span>
784
+ <PluginServers plugin={plugin} status={status} />
785
+ </div>
786
+ );
787
+ }
788
+
789
+ function PluginServers({ plugin, status }: { plugin: Plugin; status: PluginStatus | null }) {
790
+ if (!status || status.instances.length === 0) {
791
+ return <span className="text-xs text-text-muted">Server status unknown</span>;
792
+ }
793
+ const current: PluginInstanceStatus[] = status.instances.filter((instance) => instance.hash === status.hash);
794
+ const loaded = current.filter((instance) =>
795
+ instance.loaded.some((entry) => entry.name === plugin.name && entry.version === plugin.packageVersion),
796
+ ).length;
797
+ const errors = current.flatMap((instance) =>
798
+ instance.errors.filter((entry) => entry.name === plugin.name).map((entry) => `${instance.instance}: ${entry.message}`),
799
+ );
800
+ return (
801
+ <div className="text-xs">
802
+ <span className={loaded === status.instances.length ? "text-success font-medium" : "text-text-muted"}>
803
+ Loaded on {loaded} of {status.instances.length} {status.instances.length === 1 ? "server" : "servers"}
804
+ </span>
805
+ {errors.map((message) => (
806
+ <div key={message} className="text-danger mt-1 break-words">
807
+ {message}
808
+ </div>
809
+ ))}
810
+ </div>
811
+ );
812
+ }
813
+
814
+ function AddPluginModal({
815
+ open,
816
+ onClose,
817
+ onAdd,
818
+ }: {
819
+ open: boolean;
820
+ onClose: () => void;
821
+ /** Resolves why the plugin couldn't be added, or `null`. */
822
+ onAdd: (name: string, packageVersion: string, displayName: string) => Promise<string | null>;
823
+ }) {
824
+ const [name, setName] = useState("");
825
+ const [lookup, setLookup] = useState<PluginRegistryLookup | null>(null);
826
+ const [selectedVersion, setSelectedVersion] = useState("");
827
+ const [error, setError] = useState<string | null>(null);
828
+ const [busy, setBusy] = useState(false);
829
+ const [looking, setLooking] = useState(false);
830
+ /** Identifies the latest lookup, so a slower earlier response can't replace what it found. */
831
+ const lookupToken = useRef(0);
832
+ /** Identifies each time the dialog is opened, so an add that finishes after it was closed can't show its result. */
833
+ const openToken = useRef(0);
834
+
835
+ /** Forgets any lookup still in flight. */
836
+ function invalidateLookup() {
837
+ lookupToken.current++;
838
+ setLooking(false);
839
+ }
840
+
841
+ useEffect(() => {
842
+ if (!open) {
843
+ openToken.current++;
844
+ invalidateLookup();
845
+ setName("");
846
+ setLookup(null);
847
+ setSelectedVersion("");
848
+ setError(null);
849
+ setBusy(false);
850
+ }
851
+ }, [open]);
852
+
853
+ /** Looks up `packageName` at `packageVersion` (default: latest). `previous` is what a version change started
854
+ * from - kept, with the failure in place of its manifest, when that version can't be read. */
855
+ async function runLookup(packageName: string, packageVersion?: string, previous?: PluginRegistryLookup) {
856
+ const token = ++lookupToken.current;
857
+ setLooking(true);
858
+ setError(null);
859
+ try {
860
+ const found = await lookupPluginPackage(packageName, packageVersion);
861
+ if (token === lookupToken.current) {
862
+ setLookup(found);
863
+ setSelectedVersion(found.selected.version);
864
+ }
865
+ } catch (err) {
866
+ if (token !== lookupToken.current) {
867
+ return;
868
+ }
869
+ const message = errorMessage(err, "Could not look that package up.");
870
+ if (previous && packageVersion) {
871
+ setLookup({ ...previous, selected: { ...previous.selected, version: packageVersion, manifest: message } });
872
+ } else {
873
+ setLookup(null);
874
+ setError(message);
875
+ }
876
+ } finally {
877
+ if (token === lookupToken.current) {
878
+ setLooking(false);
879
+ }
880
+ }
881
+ }
882
+
883
+ function find(e: FormEvent) {
884
+ e.preventDefault();
885
+ if (!name.trim()) {
886
+ setError("Enter a package name.");
887
+ return;
888
+ }
889
+ void runLookup(name.trim());
890
+ }
891
+
892
+ function chooseVersion(version: string) {
893
+ setSelectedVersion(version);
894
+ // The manifest shown, and whether it's a loadable plugin, depend on the version.
895
+ void runLookup(lookup!.package.name, version, lookup!);
896
+ }
897
+
898
+ const manifest = lookup?.selected.manifest;
899
+
900
+ async function add() {
901
+ const token: number = openToken.current;
902
+ setBusy(true);
903
+ setError(null);
904
+ const name: string = lookup!.package.name;
905
+ const problem = await onAdd(name, selectedVersion, typeof manifest === "object" ? manifest.displayName : name);
906
+ if (token === openToken.current) {
907
+ setError(problem);
908
+ setBusy(false);
909
+ }
910
+ }
911
+
912
+ return (
913
+ <Modal open={open} onClose={onClose} title="Add plugin">
914
+ {error && <Alert>{error}</Alert>}
915
+ <form onSubmit={find} className="flex gap-2 items-end mb-4">
916
+ <label className="flex flex-col gap-1.5 text-sm flex-1">
917
+ <span className="font-semibold">Package name</span>
918
+ <input
919
+ aria-label="Package name"
920
+ className={INPUT_CLASS}
921
+ value={name}
922
+ placeholder="@rapidmx/activesync-plugin"
923
+ onChange={(e) => {
924
+ setName(e.target.value);
925
+ invalidateLookup();
926
+ setLookup(null);
927
+ }}
928
+ />
929
+ </label>
930
+ <Button type="submit" variant="secondary" className="!w-auto" loading={looking && !lookup} disabled={busy || looking}>
931
+ Find
932
+ </Button>
933
+ </form>
934
+ {lookup && (
935
+ <div className="flex flex-col gap-3">
936
+ {typeof manifest === "string" ? (
937
+ <>
938
+ <div className="text-sm font-semibold">{lookup.package.name}</div>
939
+ <Alert>{manifest}</Alert>
940
+ </>
941
+ ) : (
942
+ <div className="text-sm">
943
+ <div className="font-semibold">{manifest?.displayName}</div>
944
+ <div className="text-xs text-text-muted">{lookup.package.name}</div>
945
+ {manifest?.description && <div className="text-text-muted">{manifest.description}</div>}
946
+ </div>
947
+ )}
948
+ <label className="flex flex-col gap-1.5 text-sm">
949
+ <span className="font-semibold">Version</span>
950
+ <select aria-label="Version" className={INPUT_CLASS} value={selectedVersion} onChange={(e) => chooseVersion(e.target.value)}>
951
+ {lookup.package.versions.map((version) => (
952
+ <option key={version} value={version}>
953
+ {version}
954
+ {version === lookup.package.latest ? " (latest)" : ""}
955
+ </option>
956
+ ))}
957
+ </select>
958
+ </label>
959
+ <div className="flex gap-2 justify-end">
960
+ <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
961
+ Cancel
962
+ </Button>
963
+ <Button
964
+ type="button"
965
+ className="!w-auto"
966
+ loading={busy || looking}
967
+ disabled={busy || looking || typeof manifest === "string"}
968
+ onClick={() => void add()}
969
+ >
970
+ Add plugin
971
+ </Button>
972
+ </div>
973
+ </div>
974
+ )}
975
+ </Modal>
976
+ );
977
+ }
978
+
979
+ function ChangeVersionModal({
980
+ plugin,
981
+ onClose,
982
+ onSave,
983
+ }: {
984
+ plugin: Plugin;
985
+ onClose: () => void;
986
+ /** Resolves why the version couldn't be changed, or `null`. */
987
+ onSave: (packageVersion: string) => Promise<string | null>;
988
+ }) {
989
+ const [versions, setVersions] = useState<string[] | null>(null);
990
+ const [latest, setLatest] = useState<string | undefined>();
991
+ const [selected, setSelected] = useState(plugin.packageVersion);
992
+ const [error, setError] = useState<string | null>(null);
993
+ const [busy, setBusy] = useState(false);
994
+
995
+ useEffect(() => {
996
+ lookupPluginPackage(plugin.name)
997
+ .then((found) => {
998
+ setVersions(found.package.versions);
999
+ setLatest(found.package.latest);
1000
+ })
1001
+ .catch((err) => setError(errorMessage(err, "Could not load the available versions.")));
1002
+ }, [plugin.name]);
1003
+
1004
+ async function save() {
1005
+ setBusy(true);
1006
+ setError(null);
1007
+ const problem = await onSave(selected);
1008
+ if (problem) {
1009
+ setError(problem);
1010
+ setBusy(false);
1011
+ }
1012
+ }
1013
+
1014
+ return (
1015
+ <Modal open onClose={onClose} title={`${plugin.manifest.displayName} version`}>
1016
+ {error && <Alert>{error}</Alert>}
1017
+ {versions === null ? (
1018
+ !error && <p className="text-sm text-text-muted">Loading&hellip;</p>
1019
+ ) : (
1020
+ <div className="flex flex-col gap-3">
1021
+ <label className="flex flex-col gap-1.5 text-sm">
1022
+ <span className="font-semibold">Version</span>
1023
+ <select aria-label="Version" className={INPUT_CLASS} value={selected} onChange={(e) => setSelected(e.target.value)}>
1024
+ {versions.map((version) => (
1025
+ <option key={version} value={version}>
1026
+ {version}
1027
+ {version === latest ? " (latest)" : ""}
1028
+ {version === plugin.packageVersion ? " (installed)" : ""}
1029
+ </option>
1030
+ ))}
1031
+ </select>
1032
+ </label>
1033
+ <div className="flex gap-2 justify-end">
1034
+ <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1035
+ Cancel
1036
+ </Button>
1037
+ <Button
1038
+ type="button"
1039
+ className="!w-auto"
1040
+ loading={busy}
1041
+ disabled={busy || selected === plugin.packageVersion}
1042
+ onClick={() => void save()}
1043
+ >
1044
+ Save
1045
+ </Button>
1046
+ </div>
1047
+ </div>
1048
+ )}
1049
+ </Modal>
1050
+ );
1051
+ }
1052
+
1053
+ /** Lists the plugins a change also installs or enables, and makes the change once confirmed. */
1054
+ function ConfirmDependenciesModal({
1055
+ change,
1056
+ displayNameOf,
1057
+ onClose,
1058
+ onDone,
1059
+ }: {
1060
+ change: PendingChange;
1061
+ displayNameOf: (name: string) => string;
1062
+ onClose: () => void;
1063
+ onDone: () => void;
1064
+ }) {
1065
+ const [error, setError] = useState<string | null>(null);
1066
+ const [busy, setBusy] = useState(false);
1067
+ const { plan } = change;
1068
+
1069
+ async function proceed() {
1070
+ setBusy(true);
1071
+ setError(null);
1072
+ try {
1073
+ await change.apply(plan);
1074
+ onDone();
1075
+ } catch (err) {
1076
+ setError(errorMessage(err, change.failure));
1077
+ setBusy(false);
1078
+ }
1079
+ }
1080
+
1081
+ return (
1082
+ <Modal open onClose={onClose} title={`${change.displayName} requires other plugins`}>
1083
+ {error && <Alert>{error}</Alert>}
1084
+ <p className="text-sm mb-2">
1085
+ {change.displayName} {plan.plugin.version} needs these plugins, so they&apos;ll be changed too:
1086
+ </p>
1087
+ <ul className="text-sm list-disc pl-5 mb-4">
1088
+ {plan.install.map((dependency) => (
1089
+ <li key={dependency.name}>
1090
+ Install {dependency.manifest.displayName} {dependency.version}
1091
+ </li>
1092
+ ))}
1093
+ {plan.enable.map((name) => (
1094
+ <li key={name}>Enable {displayNameOf(name)}</li>
1095
+ ))}
1096
+ </ul>
1097
+ <div className="flex gap-2 justify-end">
1098
+ <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1099
+ Cancel
1100
+ </Button>
1101
+ <Button type="button" className="!w-auto" loading={busy} disabled={busy} onClick={() => void proceed()}>
1102
+ Continue
1103
+ </Button>
1104
+ </div>
1105
+ </Modal>
1106
+ );
1107
+ }
1108
+
1109
+ /** Whether a required select has no value to fall back on, so the form has to pick (and save) one. */
1110
+ function needsSelection(definition: PluginSettingDefinition, saved: PluginSettingValue | undefined): boolean {
1111
+ return (
1112
+ definition.type === "select" &&
1113
+ !!definition.required &&
1114
+ saved === undefined &&
1115
+ definition.default === undefined &&
1116
+ (definition.options ?? []).length > 0
1117
+ );
1118
+ }
1119
+
1120
+ /** A setting's current form value: its saved value, else its default - or, for a required select with neither, its
1121
+ * first option. Kept as a string for text inputs. */
1122
+ function initialValue(definition: PluginSettingDefinition, saved: PluginSettingValue | undefined): PluginSettingValue | "" {
1123
+ if (needsSelection(definition, saved)) {
1124
+ return definition.options![0].value;
1125
+ }
1126
+ const value = saved ?? definition.default;
1127
+ if (definition.type === "boolean") {
1128
+ return value === true;
1129
+ }
1130
+ return value === undefined ? "" : String(value);
1131
+ }
1132
+
1133
+ function SettingsModal({ plugin, onClose, onSaved }: { plugin: Plugin; onClose: () => void; onSaved: (plugin: Plugin) => void }) {
1134
+ // Only opened from the Settings button, which is only shown for a plugin that declares settings.
1135
+ const definitions: PluginSettingDefinition[] = plugin.manifest.settings!;
1136
+ const initial = useRef(Object.fromEntries(definitions.map((d) => [d.key, initialValue(d, plugin.settings[d.key])])));
1137
+ const [values, setValues] = useState<Record<string, PluginSettingValue | "">>(initial.current);
1138
+ const [error, setError] = useState<string | null>(null);
1139
+ const [busy, setBusy] = useState(false);
1140
+
1141
+ async function save(e: FormEvent) {
1142
+ e.preventDefault();
1143
+ // The server replaces the whole settings object, so every setting is sent. One left alone is sent as it's saved
1144
+ // - `null` when nothing is, so it keeps following the plugin's default rather than pinning the default shown.
1145
+ // A required select with nothing to fall back on is sent as the form picked it.
1146
+ const settings: Record<string, PluginSettingValue | null> = {};
1147
+ let changed = false;
1148
+ for (const definition of definitions) {
1149
+ const key: string = definition.key;
1150
+ const value = values[key];
1151
+ if (value === initial.current[key] && !needsSelection(definition, plugin.settings[key])) {
1152
+ settings[key] = plugin.settings[key] ?? null;
1153
+ continue;
1154
+ }
1155
+ changed = true;
1156
+ // A number input only ever reports a valid number or an empty string.
1157
+ settings[key] = value === "" ? null : definition.type === "number" ? Number(value) : value;
1158
+ }
1159
+ if (!changed) {
1160
+ onClose();
1161
+ return;
1162
+ }
1163
+ setBusy(true);
1164
+ setError(null);
1165
+ try {
1166
+ onSaved(await updatePlugin(plugin.uid, { version: plugin.version, settings }));
1167
+ } catch (err) {
1168
+ setError(errorMessage(err, "Could not save the settings."));
1169
+ } finally {
1170
+ setBusy(false);
1171
+ }
1172
+ }
1173
+
1174
+ return (
1175
+ <Modal open onClose={onClose} title={`${plugin.manifest.displayName} settings`}>
1176
+ {error && <Alert>{error}</Alert>}
1177
+ <form onSubmit={save} className="flex flex-col gap-5">
1178
+ {definitions.map((definition) => (
1179
+ <SettingField
1180
+ key={definition.key}
1181
+ definition={definition}
1182
+ value={values[definition.key]}
1183
+ onChange={(value) => setValues((prev) => ({ ...prev, [definition.key]: value }))}
1184
+ />
1185
+ ))}
1186
+ {/* Kept in view at the bottom of the dialog while a long list of settings scrolls. The dialog scrolls
1187
+ inside its padding, so the bar reaches past it to the dialog's edges. */}
1188
+ <div className="sticky -bottom-7 -mx-7 -mb-7 px-7 py-4 bg-surface border-t border-border flex flex-col gap-3">
1189
+ <p className="text-xs text-text-muted">Saving restarts the servers one at a time to apply the new settings.</p>
1190
+ <div className="flex gap-2 justify-end">
1191
+ <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1192
+ Cancel
1193
+ </Button>
1194
+ <Button type="submit" className="!w-auto" loading={busy} disabled={busy}>
1195
+ Save
1196
+ </Button>
1197
+ </div>
1198
+ </div>
1199
+ </form>
1200
+ </Modal>
1201
+ );
1202
+ }
1203
+
1204
+ function SettingField({
1205
+ definition,
1206
+ value,
1207
+ onChange,
1208
+ }: {
1209
+ definition: PluginSettingDefinition;
1210
+ value: PluginSettingValue | "";
1211
+ onChange: (value: PluginSettingValue | "") => void;
1212
+ }) {
1213
+ const help = definition.help && <span className="text-xs text-text-muted">{definition.help}</span>;
1214
+ if (definition.type === "boolean") {
1215
+ // Laid out like the admin policy forms' checkboxes: the help sits under the label, beside the box.
1216
+ return (
1217
+ <label className="flex items-start gap-2 text-sm">
1218
+ <input type="checkbox" className="mt-1" checked={value === true} onChange={(e) => onChange(e.target.checked)} />
1219
+ <span className="flex flex-col gap-0.5">
1220
+ <span className="font-semibold">{definition.label}</span>
1221
+ {help}
1222
+ </span>
1223
+ </label>
1224
+ );
1225
+ }
1226
+ return (
1227
+ <label className="flex flex-col gap-1.5 text-sm">
1228
+ <span className="font-semibold">{definition.label}</span>
1229
+ {definition.type === "select" ? (
1230
+ <select aria-label={definition.label} className={INPUT_CLASS} value={String(value)} onChange={(e) => onChange(e.target.value)}>
1231
+ {!definition.required && <option value="">Default</option>}
1232
+ {(definition.options ?? []).map((option) => (
1233
+ <option key={option.value} value={option.value}>
1234
+ {option.label}
1235
+ </option>
1236
+ ))}
1237
+ </select>
1238
+ ) : (
1239
+ <input
1240
+ aria-label={definition.label}
1241
+ className={INPUT_CLASS}
1242
+ type={definition.type === "number" ? "number" : "text"}
1243
+ min={definition.min}
1244
+ max={definition.max}
1245
+ required={definition.required}
1246
+ value={String(value)}
1247
+ onChange={(e) => onChange(e.target.value)}
1248
+ />
1249
+ )}
1250
+ {help}
1251
+ </label>
1252
+ );
1253
+ }
1254
+
1255
+ function RemoveModal({ plugin, onClose, onRemoved }: { plugin: Plugin; onClose: () => void; onRemoved: () => void }) {
1256
+ const [error, setError] = useState<string | null>(null);
1257
+ const [busy, setBusy] = useState(false);
1258
+
1259
+ async function remove() {
1260
+ setBusy(true);
1261
+ setError(null);
1262
+ try {
1263
+ await removePlugin(plugin.uid);
1264
+ onRemoved();
1265
+ } catch (err) {
1266
+ setError(errorMessage(err, "Could not uninstall the plugin."));
1267
+ setBusy(false);
1268
+ }
1269
+ }
1270
+
1271
+ return (
1272
+ <Modal open onClose={onClose} title={`Uninstall ${plugin.manifest.displayName}?`}>
1273
+ {error && <Alert>{error}</Alert>}
1274
+ <p className="text-sm mb-4">
1275
+ The servers stop running this plugin after they restart. Data it stored stays in the database, and adding
1276
+ the plugin again brings it back.
1277
+ </p>
1278
+ <div className="flex gap-2 justify-end">
1279
+ <Button type="button" variant="secondary" className="!w-auto" onClick={onClose}>
1280
+ Cancel
1281
+ </Button>
1282
+ <Button type="button" className="!w-auto" loading={busy} disabled={busy} onClick={() => void remove()}>
1283
+ Uninstall
1284
+ </Button>
1285
+ </div>
1286
+ </Modal>
1287
+ );
1288
+ }