@rapidmx/web-client 0.4.0 → 0.5.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 (169) hide show
  1. package/apps/admin/audit-log/index.tsx +35 -8
  2. package/apps/admin/data-requests/index.tsx +480 -485
  3. package/apps/admin/distribution-lists/[uid].tsx +19 -1
  4. package/apps/admin/escrow-scopes/[uid].tsx +348 -237
  5. package/apps/admin/escrow-scopes/new/index.tsx +8 -2
  6. package/apps/admin/index.tsx +19 -1
  7. package/apps/admin/ingest-queue/index.tsx +44 -5
  8. package/apps/admin/mailboxes/[uid].tsx +211 -184
  9. package/apps/admin/quarantine/index.tsx +46 -14
  10. package/apps/admin/transport-rules/[uid].tsx +30 -1
  11. package/apps/admin/transport-rules/_transportRuleConfig.tsx +38 -2
  12. package/apps/admin/transport-rules/index.tsx +24 -6
  13. package/apps/admin/transport-rules/new/index.tsx +30 -1
  14. package/apps/escrow/_layout.tsx +2 -3
  15. package/apps/escrow/audit-log/index.tsx +196 -168
  16. package/apps/escrow/matters/[uid].tsx +621 -521
  17. package/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.tsx +22 -1
  18. package/apps/shared/components/admin/layout/AdminShell.tsx +3 -1
  19. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -0
  20. package/apps/shared/components/admin/mailboxes/ResourceSettingsCard.tsx +3 -3
  21. package/apps/shared/components/admin/mailboxes/ShareAccessCard.tsx +55 -11
  22. package/apps/shared/components/admin/settings/BrandingForm.tsx +15 -4
  23. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +18 -7
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +10 -2
  25. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +6 -0
  26. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +45 -12
  27. package/apps/shared/components/admin/settings/PluginsManager.tsx +1235 -595
  28. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +174 -98
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +49 -13
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +150 -34
  31. package/apps/shared/components/admin/signOut.ts +79 -0
  32. package/apps/shared/components/admin/usePagedList.tsx +129 -0
  33. package/apps/shared/components/calendar/EventModal.tsx +717 -549
  34. package/apps/shared/components/calendar/MonthView.tsx +173 -139
  35. package/apps/shared/components/calendar/RecurrenceEditor.tsx +222 -180
  36. package/apps/shared/components/calendar/SplitDayView.tsx +143 -137
  37. package/apps/shared/components/calendar/TimeGridView.tsx +244 -198
  38. package/apps/shared/components/calendar/allDay.ts +124 -0
  39. package/apps/shared/components/calendar/layout/CalendarShell.tsx +1 -1
  40. package/apps/shared/components/contacts/ContactDetailPane.tsx +100 -21
  41. package/apps/shared/components/contacts/ContactForm.tsx +377 -348
  42. package/apps/shared/components/contacts/ContactsSidebar.tsx +6 -2
  43. package/apps/shared/components/contacts/KeyChangeReview.tsx +192 -0
  44. package/apps/shared/components/contacts/contactKeys.ts +78 -0
  45. package/apps/shared/components/escrow/layout/EscrowShell.tsx +148 -134
  46. package/apps/shared/components/layout/AppShell.tsx +87 -15
  47. package/apps/shared/components/layout/BrandingChrome.tsx +48 -10
  48. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +389 -298
  49. package/apps/shared/components/layout/MailboxProvisioning.tsx +19 -3
  50. package/apps/shared/components/layout/RecoveryCodeUnlock.tsx +350 -0
  51. package/apps/shared/components/layout/UnlockPromptProvider.tsx +257 -128
  52. package/apps/shared/components/mail/ConversationThreadPane.tsx +216 -181
  53. package/apps/shared/components/mail/MessageDetailPane.tsx +1318 -630
  54. package/apps/shared/components/mail/compose/ComposeContext.tsx +20 -15
  55. package/apps/shared/components/mail/compose/ComposeWindow.tsx +854 -132
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -0
  57. package/apps/shared/components/mail/layout/MailShell.tsx +12 -2
  58. package/apps/shared/components/mail/pinnedSigners.ts +124 -0
  59. package/apps/shared/components/mail/verificationSeals.ts +125 -0
  60. package/apps/shared/components/mail/writableMailboxes.ts +101 -0
  61. package/apps/shared/components/rules/RuleBuilder.tsx +311 -276
  62. package/apps/shared/mail/listAllPages.ts +39 -0
  63. package/apps/shared/search/LocalIndexLifecycle.tsx +64 -55
  64. package/apps/shared/search/localIndexBuilder.ts +481 -179
  65. package/apps/shared/search/localIndexRpcClient.ts +228 -28
  66. package/apps/shared/search/localIndexSchema.ts +15 -6
  67. package/apps/shared/search/localIndexStorage.ts +98 -0
  68. package/apps/shared/search/localIndexVFS.ts +32 -1
  69. package/apps/shared/search/localIndexWorker.ts +648 -186
  70. package/apps/www/calendar/index.tsx +438 -417
  71. package/apps/www/contacts/[uid].tsx +21 -2
  72. package/apps/www/contacts/index.tsx +116 -12
  73. package/apps/www/index.tsx +1314 -1041
  74. package/apps/www/messages/[uid].tsx +18 -6
  75. package/apps/www/settings/auto-reply/index.tsx +134 -129
  76. package/apps/www/settings/booking-types/[uid].tsx +306 -300
  77. package/apps/www/settings/encryption/index.tsx +739 -216
  78. package/apps/www/settings/filters/[uid].tsx +171 -155
  79. package/apps/www/settings/filters/new/index.tsx +8 -1
  80. package/apps/www/settings/focused-inbox/index.tsx +150 -148
  81. package/apps/www/settings/privacy/index.tsx +494 -436
  82. package/apps/www/settings/read-receipts/index.tsx +148 -125
  83. package/apps/www/settings/sharing/index.tsx +17 -14
  84. package/apps/www/tasks/index.tsx +638 -579
  85. package/dist/apps/admin/audit-log/index.js +38 -8
  86. package/dist/apps/admin/data-requests/index.js +52 -72
  87. package/dist/apps/admin/distribution-lists/[uid].js +1 -1
  88. package/dist/apps/admin/escrow-scopes/[uid].js +91 -12
  89. package/dist/apps/admin/escrow-scopes/new/index.js +8 -3
  90. package/dist/apps/admin/index.js +4 -1
  91. package/dist/apps/admin/ingest-queue/index.js +24 -6
  92. package/dist/apps/admin/mailboxes/[uid].js +20 -4
  93. package/dist/apps/admin/quarantine/index.js +20 -11
  94. package/dist/apps/admin/transport-rules/[uid].js +18 -2
  95. package/dist/apps/admin/transport-rules/_transportRuleConfig.js +19 -0
  96. package/dist/apps/admin/transport-rules/index.js +22 -6
  97. package/dist/apps/admin/transport-rules/new/index.js +18 -2
  98. package/dist/apps/escrow/_layout.js +3 -3
  99. package/dist/apps/escrow/audit-log/index.js +26 -1
  100. package/dist/apps/escrow/matters/[uid].js +77 -42
  101. package/dist/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.js +11 -2
  102. package/dist/apps/shared/components/admin/layout/AdminShell.js +3 -1
  103. package/dist/apps/shared/components/admin/mailboxes/EscrowScopeCard.js +72 -0
  104. package/dist/apps/shared/components/admin/mailboxes/ResourceSettingsCard.js +3 -3
  105. package/dist/apps/shared/components/admin/mailboxes/ShareAccessCard.js +22 -4
  106. package/dist/apps/shared/components/admin/settings/BrandingForm.js +15 -4
  107. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +13 -7
  108. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +7 -2
  109. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +6 -0
  110. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +34 -12
  111. package/dist/apps/shared/components/admin/settings/PluginsManager.js +390 -78
  112. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +40 -11
  113. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +29 -13
  114. package/dist/apps/shared/components/admin/setup/SetupWizard.js +87 -21
  115. package/dist/apps/shared/components/admin/signOut.js +75 -0
  116. package/dist/apps/shared/components/admin/usePagedList.js +99 -0
  117. package/dist/apps/shared/components/calendar/EventModal.js +142 -21
  118. package/dist/apps/shared/components/calendar/MonthView.js +12 -5
  119. package/dist/apps/shared/components/calendar/RecurrenceEditor.js +40 -5
  120. package/dist/apps/shared/components/calendar/SplitDayView.js +10 -4
  121. package/dist/apps/shared/components/calendar/TimeGridView.js +23 -7
  122. package/dist/apps/shared/components/calendar/allDay.js +111 -0
  123. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +1 -1
  124. package/dist/apps/shared/components/contacts/ContactDetailPane.js +43 -5
  125. package/dist/apps/shared/components/contacts/ContactForm.js +32 -10
  126. package/dist/apps/shared/components/contacts/ContactsSidebar.js +2 -2
  127. package/dist/apps/shared/components/contacts/KeyChangeReview.js +63 -0
  128. package/dist/apps/shared/components/contacts/contactKeys.js +64 -0
  129. package/dist/apps/shared/components/escrow/layout/EscrowShell.js +24 -5
  130. package/dist/apps/shared/components/layout/AppShell.js +83 -14
  131. package/dist/apps/shared/components/layout/BrandingChrome.js +45 -10
  132. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +49 -12
  133. package/dist/apps/shared/components/layout/MailboxProvisioning.js +10 -2
  134. package/dist/apps/shared/components/layout/RecoveryCodeUnlock.js +174 -0
  135. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +73 -14
  136. package/dist/apps/shared/components/mail/ConversationThreadPane.js +50 -12
  137. package/dist/apps/shared/components/mail/MessageDetailPane.js +441 -36
  138. package/dist/apps/shared/components/mail/compose/ComposeContext.js +9 -6
  139. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +699 -128
  140. package/dist/apps/shared/components/mail/compose/composeFlushRegistry.js +50 -0
  141. package/dist/apps/shared/components/mail/layout/MailShell.js +12 -3
  142. package/dist/apps/shared/components/mail/pinnedSigners.js +98 -0
  143. package/dist/apps/shared/components/mail/verificationSeals.js +112 -0
  144. package/dist/apps/shared/components/mail/writableMailboxes.js +87 -0
  145. package/dist/apps/shared/components/rules/RuleBuilder.js +34 -6
  146. package/dist/apps/shared/mail/listAllPages.js +25 -0
  147. package/dist/apps/shared/search/LocalIndexLifecycle.js +58 -54
  148. package/dist/apps/shared/search/localIndexBuilder.js +292 -37
  149. package/dist/apps/shared/search/localIndexRpcClient.js +188 -25
  150. package/dist/apps/shared/search/localIndexSchema.js +12 -6
  151. package/dist/apps/shared/search/localIndexStorage.js +86 -0
  152. package/dist/apps/shared/search/localIndexVFS.js +68 -40
  153. package/dist/apps/shared/search/localIndexWorker.js +519 -173
  154. package/dist/apps/www/calendar/index.js +28 -10
  155. package/dist/apps/www/contacts/[uid].js +13 -2
  156. package/dist/apps/www/contacts/index.js +80 -10
  157. package/dist/apps/www/index.js +339 -108
  158. package/dist/apps/www/messages/[uid].js +18 -6
  159. package/dist/apps/www/settings/auto-reply/index.js +9 -4
  160. package/dist/apps/www/settings/booking-types/[uid].js +17 -12
  161. package/dist/apps/www/settings/encryption/index.js +514 -97
  162. package/dist/apps/www/settings/filters/[uid].js +22 -7
  163. package/dist/apps/www/settings/filters/new/index.js +8 -2
  164. package/dist/apps/www/settings/focused-inbox/index.js +3 -1
  165. package/dist/apps/www/settings/privacy/index.js +57 -22
  166. package/dist/apps/www/settings/read-receipts/index.js +10 -3
  167. package/dist/apps/www/settings/sharing/index.js +7 -11
  168. package/dist/apps/www/tasks/index.js +50 -10
  169. package/package.json +2 -2
@@ -9,35 +9,64 @@
9
9
  * a per-mailbox connection map (see that file's own doc comment).
10
10
  *
11
11
  * `postMessage` has no native request/response pairing, so every call generates its own numeric `id` and
12
- * this module correlates the eventual matching response via a pending-request map - the same shape the
13
- * `__spike__` validation harness used during development, now the real thing.
12
+ * this module correlates the eventual matching response via a pending-request map.
13
+ *
14
+ * **Generations**: `nextLocalIndexGeneration()` hands out one monotonic counter shared by build passes and
15
+ * destroys, so the Worker can reject a build call issued before the index was destroyed (see
16
+ * `GenerationParams`).
17
+ *
18
+ * **Sign-out reaches every tab**: `destroyAllLocalIndexes()` broadcasts on a `BroadcastChannel`; any other
19
+ * tab running a Worker closes its connections and refuses further `init`s.
20
+ *
21
+ * **Failed deletions are retried**: a destroy that couldn't remove a directory (another tab held it, the page
22
+ * navigated away first) is recorded in `localStorage` and retried before this tab's first `init`.
14
23
  */
15
24
  import type { ParsedSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
16
25
  import type {
17
26
  Coverage,
27
+ DestroyParams,
28
+ GenerationParams,
18
29
  IndexEntitiesParams,
30
+ IndexEntitiesResult,
31
+ IndexedVersionsParams,
19
32
  InitParams,
20
33
  LocalIndexRequest,
21
34
  LocalIndexResponse,
22
35
  LocalSearchPage,
36
+ MoveEntityParams,
37
+ PruneEntitiesParams,
23
38
  RemoveEntityParams,
24
39
  SearchParams,
25
40
  SetBuildingParams,
26
41
  SetWindowParams,
42
+ WindowState,
27
43
  } from "./localIndexWorker.js";
28
44
  import type { LocalIndexEntity } from "./localIndexSchema.js";
45
+ import { removeLocalIndexDirectories, removeLocalIndexDirectory } from "./localIndexStorage.js";
29
46
 
30
47
  let worker: Worker | undefined;
31
48
  let nextRequestId = 1;
32
49
  const pending = new Map<number, { resolve: (value: unknown) => void; reject: (err: Error) => void }>();
33
50
 
34
- /** Every mailboxUid `initLocalIndex()` has opened this session, not yet `destroyLocalIndex()`-ed - lets
35
- * `destroyAllLocalIndexes()` (called from `AppShell.tsx`'s sign-out, which has no mailboxUid of its own
36
- * to pass - see that call site's own comment) destroy every open index without needing one threaded
37
- * through. Mirrors `keySession.ts`'s own module-level `sessions` map in spirit - session-scoped,
38
- * intentionally never persisted. */
51
+ /** Every mailboxUid `initLocalIndex()` has opened this session, not yet `destroyLocalIndex()`-ed. Gates
52
+ * the in-session mutation helpers (`removeLocalEntity()`/`moveLocalEntity()`) so a delete/move in a
53
+ * mailbox this tab never indexed doesn't spin up the Worker just to no-op. */
39
54
  const initializedMailboxes = new Set<string>();
40
55
 
56
+ let generationCounter = 0;
57
+
58
+ /** A fresh generation - see this module's doc comment. */
59
+ export function nextLocalIndexGeneration(): number {
60
+ generationCounter += 1;
61
+ return generationCounter;
62
+ }
63
+
64
+ /** Set once this tab (or another one) signed out - no index may be opened again in this page load. */
65
+ let signedOut = false;
66
+
67
+ export const SIGN_OUT_CHANNEL = "rapidmx-localsearch";
68
+ let channel: BroadcastChannel | undefined;
69
+
41
70
  function getWorker(): Worker {
42
71
  if (!worker) {
43
72
  worker = new Worker(new URL("./localIndexWorker.ts", import.meta.url), { type: "module" });
@@ -53,29 +82,147 @@ function getWorker(): Worker {
53
82
  entry.reject(new Error(event.data.error));
54
83
  }
55
84
  });
85
+ // Only a tab with a Worker has connections to close when another tab signs out.
86
+ listenForSignOut();
56
87
  }
57
88
  return worker;
58
89
  }
59
90
 
91
+ function getChannel(): BroadcastChannel | undefined {
92
+ if (!channel && typeof BroadcastChannel !== "undefined") {
93
+ channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
94
+ }
95
+ return channel;
96
+ }
97
+
98
+ function listenForSignOut(): void {
99
+ getChannel()?.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
100
+ if (event.data?.type === "sign-out") {
101
+ void closeEverythingInThisTab();
102
+ }
103
+ });
104
+ }
105
+
106
+ /** Another tab signed out: stop every build here and close this tab's connections (which also removes their
107
+ * directories, now that nothing holds them open). Never rejects. */
108
+ async function closeEverythingInThisTab(): Promise<void> {
109
+ signedOut = true;
110
+ initializedMailboxes.clear();
111
+ await call("destroyAll", { generation: nextLocalIndexGeneration() } satisfies GenerationParams).catch(() => undefined);
112
+ }
113
+
60
114
  function call<T>(method: LocalIndexRequest["method"], params?: unknown): Promise<T> {
61
115
  const id = nextRequestId++;
62
116
  return new Promise<T>((resolve, reject) => {
63
117
  pending.set(id, { resolve: resolve as (value: unknown) => void, reject });
64
- getWorker().postMessage({ id, method, params } satisfies LocalIndexRequest);
118
+ try {
119
+ getWorker().postMessage({ id, method, params } satisfies LocalIndexRequest);
120
+ } catch (err) {
121
+ pending.delete(id);
122
+ reject(err instanceof Error ? err : new Error(String(err)));
123
+ }
65
124
  });
66
125
  }
67
126
 
127
+ export const PENDING_DELETIONS_KEY = "rapidmx-localsearch-pending-deletions";
128
+ /** Stands for "every index on this device" in the pending-deletions list - recorded before a sign-out starts,
129
+ * so a navigation that kills it midway still gets finished on the next load. */
130
+ const ALL_INDEXES = "*";
131
+
132
+ function readPendingDeletions(): string[] {
133
+ try {
134
+ const parsed: unknown = JSON.parse(localStorage.getItem(PENDING_DELETIONS_KEY) ?? "[]");
135
+ return Array.isArray(parsed) ? parsed.filter((uid): uid is string => typeof uid === "string") : [];
136
+ } catch {
137
+ return [];
138
+ }
139
+ }
140
+
141
+ function writePendingDeletions(uids: Iterable<string>): void {
142
+ try {
143
+ const list = [...new Set(uids)];
144
+ if (list.length === 0) {
145
+ localStorage.removeItem(PENDING_DELETIONS_KEY);
146
+ } else {
147
+ localStorage.setItem(PENDING_DELETIONS_KEY, JSON.stringify(list));
148
+ }
149
+ } catch {
150
+ // Storage blocked - nothing to retry from, the same as before this existed.
151
+ }
152
+ }
153
+
154
+ function updatePendingDeletions(update: (current: Set<string>) => void): void {
155
+ const current = new Set(readPendingDeletions());
156
+ update(current);
157
+ writePendingDeletions(current);
158
+ }
159
+
160
+ let pendingRetry: Promise<void> | undefined;
161
+
162
+ /** Retries every deletion an earlier page load couldn't finish. Runs once per page load (memoized), before
163
+ * this tab's first `init` - so it never races an index this tab itself opens. Never rejects. */
164
+ export function retryPendingLocalIndexDeletions(): Promise<void> {
165
+ pendingRetry ??= (async () => {
166
+ const uids = readPendingDeletions();
167
+ if (uids.length === 0) {
168
+ return;
169
+ }
170
+ const failed: string[] = [];
171
+ if (uids.includes(ALL_INDEXES)) {
172
+ const result = await removeLocalIndexDirectories().catch(() => ({ failed: [ALL_INDEXES] }));
173
+ failed.push(...result.failed);
174
+ } else {
175
+ for (const uid of uids) {
176
+ await removeLocalIndexDirectory(uid).catch(() => failed.push(uid));
177
+ }
178
+ }
179
+ writePendingDeletions(failed);
180
+ })();
181
+ return pendingRetry;
182
+ }
183
+
68
184
  export async function initLocalIndex(params: InitParams): Promise<void> {
185
+ await retryPendingLocalIndexDeletions();
186
+ if (signedOut) {
187
+ throw new Error("Signed out - the local search index is unavailable in this tab.");
188
+ }
69
189
  await call("init", params);
70
190
  initializedMailboxes.add(params.mailboxUid);
71
191
  }
72
192
 
73
- export function indexLocalEntities(mailboxUid: string, entities: LocalIndexEntity[]): Promise<void> {
74
- return call("indexEntities", { mailboxUid, entities } satisfies IndexEntitiesParams);
193
+ export function indexLocalEntities(mailboxUid: string, entities: LocalIndexEntity[], generation?: number): Promise<IndexEntitiesResult> {
194
+ return call("indexEntities", { mailboxUid, entities, generation } satisfies IndexEntitiesParams);
195
+ }
196
+
197
+ /** Drops one message from this session's local index (a delete). A no-op for a mailbox not indexed in
198
+ * this tab - a later build pass prunes it instead. Never rejects: best-effort housekeeping. */
199
+ export async function removeLocalEntity(mailboxUid: string, entityUid: string): Promise<void> {
200
+ if (!initializedMailboxes.has(mailboxUid)) {
201
+ return;
202
+ }
203
+ await call("removeEntity", { mailboxUid, entityUid } satisfies RemoveEntityParams).catch(() => undefined);
204
+ }
205
+
206
+ /** Re-points one indexed message at its new folder (archive, cancel-scheduled-send) so `folder:`-scoped
207
+ * local searches stay correct. Same no-op/never-rejects rules as `removeLocalEntity()`. */
208
+ export async function moveLocalEntity(mailboxUid: string, entityUid: string, folderUid: string): Promise<void> {
209
+ if (!initializedMailboxes.has(mailboxUid)) {
210
+ return;
211
+ }
212
+ await call("moveEntity", { mailboxUid, entityUid, folderUid } satisfies MoveEntityParams).catch(() => undefined);
213
+ }
214
+
215
+ export function getIndexedVersions(mailboxUid: string, entityUids: string[]): Promise<Record<string, string>> {
216
+ return call("indexedVersions", { mailboxUid, entityUids } satisfies IndexedVersionsParams);
75
217
  }
76
218
 
77
- export function removeLocalEntity(mailboxUid: string, entityUid: string): Promise<void> {
78
- return call("removeEntity", { mailboxUid, entityUid } satisfies RemoveEntityParams);
219
+ export function pruneLocalEntities(
220
+ mailboxUid: string,
221
+ keepEntityUids: string[],
222
+ since: string | undefined,
223
+ options: { folderUids?: string[]; generation?: number } = {},
224
+ ): Promise<number> {
225
+ return call("pruneEntities", { mailboxUid, keepEntityUids, since, ...options } satisfies PruneEntitiesParams);
79
226
  }
80
227
 
81
228
  export function searchLocal(mailboxUid: string, parsed: ParsedSearchQuery, limit: number, offset = 0): Promise<LocalSearchPage> {
@@ -86,31 +233,84 @@ export function getLocalCoverage(mailboxUid: string): Promise<Coverage> {
86
233
  return call("coverage", mailboxUid);
87
234
  }
88
235
 
89
- export function setLocalIndexWindow(mailboxUid: string, timeFloorMonths: number, byteBudgetBytes: number): Promise<void> {
90
- return call("setWindow", { mailboxUid, timeFloorMonths, byteBudgetBytes } satisfies SetWindowParams);
236
+ export function setLocalIndexWindow(mailboxUid: string, timeFloorMonths: number, byteBudgetBytes: number, generation?: number): Promise<WindowState> {
237
+ return call("setWindow", { mailboxUid, timeFloorMonths, byteBudgetBytes, generation } satisfies SetWindowParams);
91
238
  }
92
239
 
93
- export function setLocalIndexBuilding(mailboxUid: string, building: boolean): Promise<void> {
94
- return call("setBuilding", { mailboxUid, building } satisfies SetBuildingParams);
240
+ export function setLocalIndexBuilding(
241
+ mailboxUid: string,
242
+ building: boolean,
243
+ completion: { complete: boolean; coveredFrom?: string; coveredUntil?: string; generation?: number } = { complete: false },
244
+ ): Promise<void> {
245
+ return call("setBuilding", { mailboxUid, building, ...completion } satisfies SetBuildingParams);
95
246
  }
96
247
 
97
248
  /** Destroys one mailbox's local index (both the SQLite connection and its on-disk OPFS storage) - spec
98
- * §11 "MUST be destroyed on the same events that destroy private keys." Never throws: called from
99
- * lifecycle hooks (idle timeout, logout, the manual "destroy keys now" button) where a destroy failure
100
- * shouldn't block the key-destruction it's piggybacking on. */
101
- export async function destroyLocalIndex(mailboxUid: string): Promise<void> {
249
+ * §11 "MUST be destroyed on the same events that destroy private keys." Never rejects (it's called from
250
+ * lifecycle hooks where a failure mustn't block key destruction) but resolves `false` - and logs why -
251
+ * when the index could not be removed, e.g. because another tab still has it open; the deletion is then
252
+ * retried on the next page load. */
253
+ export async function destroyLocalIndex(mailboxUid: string): Promise<boolean> {
254
+ updatePendingDeletions((current) => current.add(mailboxUid));
102
255
  try {
103
- await call("destroy", mailboxUid);
104
- } catch {
105
- // Best-effort - see this function's own doc comment.
256
+ await call("destroy", { mailboxUid, generation: nextLocalIndexGeneration() } satisfies DestroyParams);
257
+ updatePendingDeletions((current) => current.delete(mailboxUid));
258
+ return true;
259
+ } catch (err) {
260
+ // `call()` only ever rejects with an Error.
261
+ console.warn(`Could not destroy the local search index for mailbox ${mailboxUid}: ${(err as Error).message}`);
262
+ return false;
106
263
  } finally {
107
264
  initializedMailboxes.delete(mailboxUid);
108
265
  }
109
266
  }
110
267
 
111
- /** Destroys every mailbox's local index this session has opened - for a caller (`AppShell.tsx`'s
112
- * sign-out) that has no specific mailboxUid of its own, the same "clear everything" shape
113
- * `destroyUnlockedKeys()` itself offers when called with no argument. */
114
- export async function destroyAllLocalIndexes(): Promise<void> {
115
- await Promise.all([...initializedMailboxes].map((mailboxUid) => destroyLocalIndex(mailboxUid)));
268
+ /** How long sign-out waits for local index destruction before navigating anyway. */
269
+ export const DESTROY_ALL_TIMEOUT_MS = 3_000;
270
+
271
+ /**
272
+ * Destroys **every** local index on this device - not just the mailboxes this page load opened (sign-out
273
+ * from Calendar, say, never opened any), by enumerating OPFS for the index directory prefix - and tells every
274
+ * other tab to close its own connections. Closes this tab's own open connections through the Worker first
275
+ * (only if one was ever spawned - there's nothing to close otherwise, and booting one just to delete files
276
+ * would be waste), then removes the directories. Anything left behind is retried on the next load. Resolves
277
+ * `true` when everything was removed within `timeoutMs`; never rejects.
278
+ */
279
+ export async function destroyAllLocalIndexes(timeoutMs = DESTROY_ALL_TIMEOUT_MS): Promise<boolean> {
280
+ signedOut = true;
281
+ writePendingDeletions([ALL_INDEXES]);
282
+ try {
283
+ getChannel()?.postMessage({ type: "sign-out" });
284
+ } catch {
285
+ // A closed/unsupported channel only loses the cross-tab notification.
286
+ }
287
+ const work = (async () => {
288
+ let ok = true;
289
+ if (worker) {
290
+ const { failed } = await call<{ failed: string[] }>("destroyAll", { generation: nextLocalIndexGeneration() } satisfies GenerationParams).catch(() => ({
291
+ failed: ["(worker)"],
292
+ }));
293
+ ok = failed.length === 0;
294
+ }
295
+ initializedMailboxes.clear();
296
+ const { failed } = await removeLocalIndexDirectories();
297
+ writePendingDeletions(failed);
298
+ return ok && failed.length === 0;
299
+ })().catch(() => false);
300
+ let timer: ReturnType<typeof setTimeout> | undefined;
301
+ const timeout = new Promise<boolean>((resolve) => {
302
+ timer = setTimeout(() => resolve(false), timeoutMs);
303
+ });
304
+ const result = await Promise.race([work, timeout]);
305
+ clearTimeout(timer);
306
+ if (!result) {
307
+ console.warn("Could not destroy every local search index before signing out.");
308
+ }
309
+ return result;
310
+ }
311
+
312
+ /** Removes local indexes for mailboxes outside `accessibleMailboxUids` - e.g. left behind by a different
313
+ * user who signed in on this device without signing out. Never rejects. */
314
+ export async function pruneInaccessibleLocalIndexes(accessibleMailboxUids: Iterable<string>): Promise<void> {
315
+ await removeLocalIndexDirectories(new Set(accessibleMailboxUids)).catch(() => undefined);
116
316
  }
@@ -15,8 +15,11 @@
15
15
  */
16
16
 
17
17
  /** Bump whenever `CREATE_SCHEMA_SQL` changes in a way existing on-disk databases can't be reconciled
18
- * with in place. */
19
- export const SCHEMA_VERSION = 1;
18
+ * with in place. A mismatch deletes and recreates the whole database file (not just its rows), so
19
+ * creation-time-only settings like `auto_vacuum` also apply to upgraded indexes.
20
+ *
21
+ * 2 - added `entities.entity_version` (incremental rebuild skip) and `auto_vacuum=INCREMENTAL`. */
22
+ export const SCHEMA_VERSION = 2;
20
23
 
21
24
  /**
22
25
  * `entities` is the real row store (metadata + the plaintext content fields), `entities_fts` is an FTS5
@@ -51,7 +54,8 @@ CREATE TABLE IF NOT EXISTS entities (
51
54
  subject TEXT,
52
55
  body TEXT,
53
56
  attachment_text TEXT,
54
- byte_size INTEGER NOT NULL DEFAULT 0
57
+ byte_size INTEGER NOT NULL DEFAULT 0,
58
+ entity_version TEXT
55
59
  );
56
60
  CREATE INDEX IF NOT EXISTS idx_entities_date ON entities(date_for_sort);
57
61
  CREATE INDEX IF NOT EXISTS idx_entities_mailbox ON entities(mailbox_uid);
@@ -105,18 +109,22 @@ export interface LocalIndexEntity {
105
109
  /** Rough on-disk cost of this entity's own content, in bytes - what `localIndexBuilder.ts`'s
106
110
  * byte-budget accounting (spec §11) sums against the configured budget. */
107
111
  byteSize: number;
112
+ /** Opaque change marker for the source entity (the builder uses the message's `version` plus its
113
+ * folder) - lets a rebuild skip re-fetching/decrypting anything already indexed unchanged. */
114
+ entityVersion?: string;
108
115
  }
109
116
 
110
117
  /** `entity_uid` upsert - `ON CONFLICT` (SQLite's UPSERT syntax) rather than a separate delete-then-insert,
111
118
  * so re-indexing an already-present message (a flag changed, a folder move) updates it in place and the
112
119
  * `entities_au` trigger keeps `entities_fts` in sync automatically. */
113
120
  export const UPSERT_ENTITY_SQL = `
114
- INSERT INTO entities (entity_type, entity_uid, mailbox_uid, folder_uid, date_for_sort, participants, flags, has_attachments, subject, body, attachment_text, byte_size)
115
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
121
+ INSERT INTO entities (entity_type, entity_uid, mailbox_uid, folder_uid, date_for_sort, participants, flags, has_attachments, subject, body, attachment_text, byte_size, entity_version)
122
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
116
123
  ON CONFLICT(entity_uid) DO UPDATE SET
117
124
  folder_uid = excluded.folder_uid, date_for_sort = excluded.date_for_sort, participants = excluded.participants,
118
125
  flags = excluded.flags, has_attachments = excluded.has_attachments, subject = excluded.subject,
119
- body = excluded.body, attachment_text = excluded.attachment_text, byte_size = excluded.byte_size
126
+ body = excluded.body, attachment_text = excluded.attachment_text, byte_size = excluded.byte_size,
127
+ entity_version = excluded.entity_version
120
128
  `;
121
129
 
122
130
  /** Bind values for `UPSERT_ENTITY_SQL`, in column order - kept alongside it so the two can never drift
@@ -135,6 +143,7 @@ export function entityBindValues(entity: LocalIndexEntity): (string | number)[]
135
143
  entity.body ?? null!,
136
144
  entity.attachmentText ?? null!,
137
145
  entity.byteSize,
146
+ entity.entityVersion ?? null!,
138
147
  ];
139
148
  }
140
149
 
@@ -0,0 +1,98 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ /**
6
+ * The Tier 2 local index's on-disk naming and bulk-removal helpers, shared by the Worker
7
+ * (`localIndexWorker.ts`) and the main thread (`localIndexRpcClient.ts`). Deliberately free of any
8
+ * wa-sqlite import so the main thread can use it without pulling the WASM build into its own bundle.
9
+ *
10
+ * Every mailbox's index lives in its own top-level OPFS directory named `rapidmx-localsearch-<mailboxUid>`
11
+ * (`AccessHandlePoolVFS` creates it from the VFS name). Enumerating that prefix is how sign-out destroys
12
+ * *every* index on this device - including ones for mailboxes this page load never opened, which the
13
+ * RPC client's own session-scoped bookkeeping can't know about - and how a sign-in prunes indexes left
14
+ * behind for mailboxes the current user can no longer access.
15
+ */
16
+
17
+ export const LOCAL_INDEX_POOL_PREFIX = "rapidmx-localsearch-";
18
+
19
+ /** The OPFS directory name (and `EncryptingVFS` name) a mailbox's index lives under. */
20
+ export function poolNameFor(mailboxUid: string): string {
21
+ return `${LOCAL_INDEX_POOL_PREFIX}${mailboxUid}`;
22
+ }
23
+
24
+ /** Inverse of `poolNameFor()`; `undefined` for any OPFS entry that isn't a local index directory. */
25
+ export function mailboxUidFromPoolName(name: string): string | undefined {
26
+ return name.startsWith(LOCAL_INDEX_POOL_PREFIX) && name.length > LOCAL_INDEX_POOL_PREFIX.length
27
+ ? name.slice(LOCAL_INDEX_POOL_PREFIX.length)
28
+ : undefined;
29
+ }
30
+
31
+ /** `navigator.storage.getDirectory()`, or `undefined` where OPFS isn't available at all (older browsers,
32
+ * jsdom/node) - there is nothing on disk to remove in that case. */
33
+ async function getOpfsRoot(): Promise<FileSystemDirectoryHandle | undefined> {
34
+ const storage = typeof navigator === "undefined" ? undefined : navigator.storage;
35
+ if (!storage?.getDirectory) {
36
+ return undefined;
37
+ }
38
+ return storage.getDirectory();
39
+ }
40
+
41
+ function isNotFound(err: unknown): boolean {
42
+ return (err as { name?: string } | undefined)?.name === "NotFoundError";
43
+ }
44
+
45
+ /** Removes one mailbox's index directory. Resolves quietly when it doesn't exist; rejects for any other
46
+ * failure (most commonly `NoModificationAllowedError` - another tab still holds its access handles). */
47
+ export async function removeLocalIndexDirectory(mailboxUid: string): Promise<void> {
48
+ const root = await getOpfsRoot();
49
+ if (!root) {
50
+ return;
51
+ }
52
+ try {
53
+ await root.removeEntry(poolNameFor(mailboxUid), { recursive: true });
54
+ } catch (err) {
55
+ if (!isNotFound(err)) {
56
+ throw err;
57
+ }
58
+ }
59
+ }
60
+
61
+ export interface LocalIndexRemovalResult {
62
+ removed: string[];
63
+ /** Mailbox uids whose directory could not be removed (e.g. still open in another tab). */
64
+ failed: string[];
65
+ }
66
+
67
+ /** Every mailbox uid that has a local index directory on this origin. */
68
+ export async function listLocalIndexMailboxUids(): Promise<string[]> {
69
+ const root = await getOpfsRoot();
70
+ if (!root) {
71
+ return [];
72
+ }
73
+ const mailboxUids: string[] = [];
74
+ // `keys()` is part of the OPFS spec and every browser that has `getDirectory()` at all, but isn't in
75
+ // this TypeScript version's DOM lib yet.
76
+ for await (const name of (root as unknown as { keys(): AsyncIterable<string> }).keys()) {
77
+ const mailboxUid = mailboxUidFromPoolName(name);
78
+ if (mailboxUid) {
79
+ mailboxUids.push(mailboxUid);
80
+ }
81
+ }
82
+ return mailboxUids;
83
+ }
84
+
85
+ /** Removes every local index directory on this origin except those whose mailbox uid is in `keep`. */
86
+ export async function removeLocalIndexDirectories(keep: ReadonlySet<string> = new Set()): Promise<LocalIndexRemovalResult> {
87
+ const result: LocalIndexRemovalResult = { removed: [], failed: [] };
88
+ const mailboxUids = (await listLocalIndexMailboxUids()).filter((mailboxUid) => !keep.has(mailboxUid));
89
+ for (const mailboxUid of mailboxUids) {
90
+ try {
91
+ await removeLocalIndexDirectory(mailboxUid);
92
+ result.removed.push(mailboxUid);
93
+ } catch {
94
+ result.failed.push(mailboxUid);
95
+ }
96
+ }
97
+ return result;
98
+ }
@@ -186,7 +186,38 @@ export class EncryptingVFS extends FacadeVFS {
186
186
  return this.#inner.jWrite(pFile, physical, blockIndex * PHYSICAL_BLOCK_SIZE);
187
187
  }
188
188
 
189
+ /** Set once any block has failed to decrypt/authenticate (or the inner VFS failed a read/write outright)
190
+ * - `localIndexWorker.ts` checks this after a failed SQLite call to tell real corruption (discard and
191
+ * rebuild, spec §11 "Invalidation") apart from an ordinary error such as a malformed FTS5 query. */
192
+ corruptionDetected = false;
193
+
194
+ /**
195
+ * `jRead`/`jWrite` MUST NOT throw: with the Asyncify build, an exception escaping an async VFS method
196
+ * never reaches the awaiting `sqlite3.*` call - it surfaces only as an unhandled rejection and the
197
+ * SQLite call hangs forever (confirmed by direct reproduction in node against the real wa-sqlite build).
198
+ * A thrown `PageCorruptedError` therefore used to wedge the whole connection instead of triggering a
199
+ * rebuild. Errors are converted to an I/O error return code here, which SQLite does propagate as a
200
+ * normal `SQLiteError`, and recorded on `corruptionDetected`.
201
+ */
189
202
  async jRead(pFile: number, pData: Uint8Array, iOffset: number): Promise<number> {
203
+ try {
204
+ return await this.#jReadBlocks(pFile, pData, iOffset);
205
+ } catch {
206
+ this.corruptionDetected = true;
207
+ return VFS.SQLITE_IOERR_READ;
208
+ }
209
+ }
210
+
211
+ async jWrite(pFile: number, pData: Uint8Array, iOffset: number): Promise<number> {
212
+ try {
213
+ return await this.#jWriteBlocks(pFile, pData, iOffset);
214
+ } catch {
215
+ this.corruptionDetected = true;
216
+ return VFS.SQLITE_IOERR_WRITE;
217
+ }
218
+ }
219
+
220
+ async #jReadBlocks(pFile: number, pData: Uint8Array, iOffset: number): Promise<number> {
190
221
  const filename = this.#filenamesByFileId.get(pFile) ?? `(unknown:${pFile})`;
191
222
  const startBlock = Math.floor(iOffset / LOGICAL_BLOCK_SIZE);
192
223
  const endBlock = Math.floor((iOffset + pData.length - 1) / LOGICAL_BLOCK_SIZE);
@@ -207,7 +238,7 @@ export class EncryptingVFS extends FacadeVFS {
207
238
  return anyAbsent ? VFS.SQLITE_IOERR_SHORT_READ : VFS.SQLITE_OK;
208
239
  }
209
240
 
210
- async jWrite(pFile: number, pData: Uint8Array, iOffset: number): Promise<number> {
241
+ async #jWriteBlocks(pFile: number, pData: Uint8Array, iOffset: number): Promise<number> {
211
242
  const filename = this.#filenamesByFileId.get(pFile) ?? `(unknown:${pFile})`;
212
243
  const startBlock = Math.floor(iOffset / LOGICAL_BLOCK_SIZE);
213
244
  const endBlock = Math.floor((iOffset + pData.length - 1) / LOGICAL_BLOCK_SIZE);