@rapidmx/web-client 0.6.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 (79) hide show
  1. package/apps/shared/components/admin/settings/BrandingForm.tsx +398 -385
  2. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -112
  3. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +159 -152
  4. package/apps/shared/components/admin/settings/PluginsManager.tsx +1288 -1235
  5. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +9 -1
  6. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -290
  7. package/apps/shared/components/admin/setup/SetupWizard.tsx +443 -416
  8. package/apps/shared/components/layout/AppShell.tsx +288 -288
  9. package/apps/shared/components/mail/ConversationList.tsx +225 -33
  10. package/apps/shared/components/mail/ConversationThreadPane.tsx +434 -216
  11. package/apps/shared/components/mail/MailListToolbar.tsx +265 -0
  12. package/apps/shared/components/mail/MailSelectionBar.tsx +222 -0
  13. package/apps/shared/components/mail/MenuButton.tsx +384 -0
  14. package/apps/shared/components/mail/MessageDetailPane.tsx +280 -215
  15. package/apps/shared/components/mail/MoveToFolderDialog.tsx +263 -0
  16. package/apps/shared/components/mail/compose/ComposeContext.tsx +29 -2
  17. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1700 -1652
  18. package/apps/shared/components/mail/compose/RecipientInput.tsx +356 -0
  19. package/apps/shared/components/mail/compose/RichTextEditor.tsx +38 -3
  20. package/apps/shared/components/mail/compose/quotedBody.ts +100 -0
  21. package/apps/shared/components/mail/compose/recipients.ts +104 -0
  22. package/apps/shared/components/mail/labelMenu.tsx +278 -0
  23. package/apps/shared/components/mail/layout/MailShell.tsx +445 -420
  24. package/apps/shared/components/mail/listPreferences.ts +228 -0
  25. package/apps/shared/components/settings/layout/SettingsShell.tsx +0 -1
  26. package/apps/shared/styles/app.css +28 -5
  27. package/apps/www/index.tsx +1854 -1314
  28. package/apps/www/messages/[uid].tsx +5 -4
  29. package/dist/apps/shared/components/admin/settings/BrandingForm.d.ts +7 -3
  30. package/dist/apps/shared/components/admin/settings/BrandingForm.js +6 -5
  31. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.d.ts +4 -1
  32. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +2 -2
  33. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.d.ts +4 -1
  34. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +2 -2
  35. package/dist/apps/shared/components/admin/settings/PluginsManager.d.ts +8 -1
  36. package/dist/apps/shared/components/admin/settings/PluginsManager.js +33 -14
  37. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.d.ts +4 -1
  38. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +2 -2
  39. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +1 -1
  40. package/dist/apps/shared/components/admin/setup/SetupWizard.js +14 -10
  41. package/dist/apps/shared/components/mail/ConversationList.d.ts +42 -6
  42. package/dist/apps/shared/components/mail/ConversationList.js +84 -10
  43. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +52 -13
  44. package/dist/apps/shared/components/mail/ConversationThreadPane.js +217 -60
  45. package/dist/apps/shared/components/mail/MailListToolbar.d.ts +55 -0
  46. package/dist/apps/shared/components/mail/MailListToolbar.js +149 -0
  47. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +59 -0
  48. package/dist/apps/shared/components/mail/MailSelectionBar.js +48 -0
  49. package/dist/apps/shared/components/mail/MenuButton.d.ts +71 -0
  50. package/dist/apps/shared/components/mail/MenuButton.js +211 -0
  51. package/dist/apps/shared/components/mail/MessageDetailPane.d.ts +27 -19
  52. package/dist/apps/shared/components/mail/MessageDetailPane.js +126 -129
  53. package/dist/apps/shared/components/mail/MoveToFolderDialog.d.ts +57 -0
  54. package/dist/apps/shared/components/mail/MoveToFolderDialog.js +138 -0
  55. package/dist/apps/shared/components/mail/compose/ComposeContext.d.ts +16 -1
  56. package/dist/apps/shared/components/mail/compose/ComposeContext.js +3 -1
  57. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +52 -20
  58. package/dist/apps/shared/components/mail/compose/RecipientInput.d.ts +36 -0
  59. package/dist/apps/shared/components/mail/compose/RecipientInput.js +203 -0
  60. package/dist/apps/shared/components/mail/compose/RichTextEditor.d.ts +10 -1
  61. package/dist/apps/shared/components/mail/compose/RichTextEditor.js +21 -3
  62. package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +37 -0
  63. package/dist/apps/shared/components/mail/compose/quotedBody.js +85 -0
  64. package/dist/apps/shared/components/mail/compose/recipients.d.ts +24 -0
  65. package/dist/apps/shared/components/mail/compose/recipients.js +87 -0
  66. package/dist/apps/shared/components/mail/labelMenu.d.ts +97 -0
  67. package/dist/apps/shared/components/mail/labelMenu.js +134 -0
  68. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +8 -0
  69. package/dist/apps/shared/components/mail/layout/MailShell.js +15 -3
  70. package/dist/apps/shared/components/mail/listPreferences.d.ts +101 -0
  71. package/dist/apps/shared/components/mail/listPreferences.js +186 -0
  72. package/dist/apps/shared/components/settings/layout/SettingsShell.js +0 -1
  73. package/dist/apps/shared/styles/app.css +28 -5
  74. package/dist/apps/www/index.js +506 -112
  75. package/dist/apps/www/messages/[uid].js +2 -3
  76. package/package.json +2 -2
  77. package/apps/www/settings/focused-inbox/index.tsx +0 -150
  78. package/dist/apps/www/settings/focused-inbox/index.d.ts +0 -4
  79. package/dist/apps/www/settings/focused-inbox/index.js +0 -71
@@ -1,1314 +1,1854 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { useCallback, useEffect, useRef, useState } from "react";
6
- import { HiOutlineLockClosed } from "react-icons/hi2";
7
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
- import { Mailbox, Message, MessageClassification, getMessage, getMessageRawContent, listMessages } from "@rapidmx/react-shared/mail/mailApi.js";
9
- import { Label, listLabels } from "@rapidmx/react-shared/mail/labelsApi.js";
10
- import { ConversationSummary, listConversations } from "@rapidmx/react-shared/mail/conversationsApi.js";
11
- import { SearchResult, search as searchMailbox } from "@rapidmx/react-shared/search/searchApi.js";
12
- import { parseSearchQuery, type ParsedSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
13
- import { normalizeServerScores } from "@rapidmx/react-shared/search/searchScoring.js";
14
- import { searchEncryptedCandidates } from "@rapidmx/react-shared/search/searchTier3.js";
15
- import { searchLocalIndex } from "../shared/search/searchTier2.js";
16
- import type { Coverage } from "../shared/search/localIndexWorker.js";
17
- import { getUnlockedKeys, subscribeKeySession, UnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
18
- import { evaluateMessageSecurity } from "@rapidmx/react-shared/crypto/messageSecurity.js";
19
- import { useMarkMessageRead, useMessageAttachments } from "@rapidmx/react-shared/mail/mailDetailHooks.js";
20
- import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
21
- import MailShell, {
22
- AggregateFolderType,
23
- MailboxFolders,
24
- MailShellProps,
25
- useMailShell,
26
- } from "../shared/components/mail/layout/MailShell.js";
27
- import MessageDetailPane from "../shared/components/mail/MessageDetailPane.js";
28
- import ConversationList from "../shared/components/mail/ConversationList.js";
29
- import ConversationThreadPane from "../shared/components/mail/ConversationThreadPane.js";
30
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
31
- import Skeleton from "@rapidmx/react-shared/components/feedback/Skeleton.js";
32
- import { useUnlockPrompt } from "../shared/components/layout/UnlockPromptProvider.js";
33
-
34
- type ViewMode = "date" | "conversation";
35
-
36
- const MESSAGE_PAGE_SIZE = 50;
37
- const SEARCH_DEBOUNCE_MS = 300;
38
- const LIST_PREVIEW_MAX_LENGTH = 160;
39
-
40
- /** The literal outer-envelope `Subject` every encrypted message carries server-side - RFC 9788's
41
- * `hcp_baseline` policy obscures it to this exact string (see `smimeMessage.ts`'s
42
- * `applyBaselineOuterHeaders()`), which is also all `Message.subject` ever shows for one of these until
43
- * decrypted client-side. Used here to recognize which loaded rows are worth decrypting for display. */
44
- const ENCRYPTED_SUBJECT_PLACEHOLDER = "[...]";
45
-
46
- /** A row's client-recovered subject/preview, once decrypted - `undefined` fields mean nothing better
47
- * than the placeholder/blank server value was recoverable for that field specifically. */
48
- interface DecryptedRow {
49
- subject?: string;
50
- preview?: string;
51
- }
52
-
53
- /** Strips HTML down to plain text, for a short list-row preview of a decrypted body - mirrors
54
- * `searchTier3.ts`'s own private `stripHtml()` (not currently exported from `@rapidmx/react-shared`,
55
- * so duplicated here rather than pulled in through a package change just for this one small, pure
56
- * helper). Not a security boundary - the output only ever feeds plain text display, truncated below,
57
- * never rendered back into any DOM. */
58
- function stripHtmlToText(html: string): string {
59
- return html
60
- .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ")
61
- .replace(/<[^>]+>/g, " ")
62
- .replace(/&nbsp;/gi, " ")
63
- .replace(/&amp;/gi, "&")
64
- .replace(/&lt;/gi, "<")
65
- .replace(/&gt;/gi, ">")
66
- .replace(/&quot;/gi, '"')
67
- .replace(/&#0*39;/gi, "'")
68
- .replace(/\s+/g, " ")
69
- .trim();
70
- }
71
-
72
- /**
73
- * Decrypts the subject/preview of every currently-loaded row whose subject is still the RFC 9788
74
- * placeholder (i.e. every encrypted message this device hasn't already resolved), keyed by uid - the
75
- * inbox-list counterpart to `MessageDetailPane`'s own single-message decrypt and `searchTier3.ts`'s
76
- * per-candidate decrypt. Bounded to `messages` (at most one loaded page, `MESSAGE_PAGE_SIZE`), never the
77
- * whole mailbox - matching `searchEncryptedCandidates()`'s own "bounded, not everything" scope. Runs only
78
- * once `unlocked` is available (the caller decides when to call this - see `InboxContent`'s own effect
79
- * and `handleUnlockList()`), and a single row's fetch/decrypt failure never blocks the rest.
80
- */
81
- async function decryptEncryptedRows(messages: Message[], unlocked: UnlockedKeys): Promise<Record<string, DecryptedRow>> {
82
- const encrypted = messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER);
83
- const entries = await Promise.all(
84
- encrypted.map(async (message): Promise<[string, DecryptedRow] | null> => {
85
- try {
86
- const rawMime = await getMessageRawContent(message.uid);
87
- const security = await evaluateMessageSecurity(rawMime, unlocked);
88
- if (!security.subject && !security.html) {
89
- return null;
90
- }
91
- const preview = security.html ? stripHtmlToText(security.html).slice(0, LIST_PREVIEW_MAX_LENGTH) : undefined;
92
- return [message.uid, { subject: security.subject, preview }];
93
- } catch {
94
- return null;
95
- }
96
- }),
97
- );
98
- const result: Record<string, DecryptedRow> = {};
99
- for (const entry of entries) {
100
- if (entry) {
101
- result[entry[0]] = entry[1];
102
- }
103
- }
104
- return result;
105
- }
106
-
107
- /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message), Tier 2 (local index, fully
108
- * decrypted and re-scored), and Tier 3 (server-narrowed candidates, decrypted and re-scored) results into
109
- * one ranked list, per `specs/search.md` §7's "client MUST re-score all results it can see... normalise
110
- * into the same space rather than interleaving raw scores": each tier is normalized independently via
111
- * `normalizeServerScores()` before merging, since a Postgres/OpenSearch score, a local `bm25()` score,
112
- * and this module's own Tier 3 term-count score all occupy unrelated ranges. A uid present in more than
113
- * one list keeps only the last-inserted entry (Tier 2 wins over Tier 3 wins over Tier 1) - Tier 2 and
114
- * Tier 3 both represent genuine, content-verified scores for the same message, so which one "wins" on
115
- * overlap doesn't change correctness, only which of two equally-valid scores is shown; either supersedes
116
- * Tier 1's metadata-only guess for the same uid.
117
- *
118
- * Called progressively - once per tier as it resolves, each time with whatever tiers have reported so
119
- * far (an empty array for the rest) - by `InboxContent`'s own search orchestration below, per §_Progressive
120
- * Results_' "reordering is permitted and preferred over appending." This function itself stays pure and
121
- * stateless; it has no notion of "in progress" versus "final." */
122
- function mergeSearchResults(tier1: SearchResult[], tier2: SearchResult[], tier3: SearchResult[]): SearchResult[] {
123
- const normalizedTier1 = normalizeServerScores(tier1);
124
- const normalizedTier2 = normalizeServerScores(tier2);
125
- const normalizedTier3 = normalizeServerScores(tier3);
126
- const merged = new Map<string, { result: SearchResult; normalizedScore: number }>();
127
- for (const entry of normalizedTier1) {
128
- merged.set(entry.result.entityUid, entry);
129
- }
130
- for (const entry of normalizedTier3) {
131
- merged.set(entry.result.entityUid, entry);
132
- }
133
- for (const entry of normalizedTier2) {
134
- merged.set(entry.result.entityUid, entry);
135
- }
136
- return Array.from(merged.values())
137
- .sort((a, b) => b.normalizedScore - a.normalizedScore)
138
- .map((entry) => entry.result);
139
- }
140
-
141
- /** `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
142
- * (contact/calendarEvent/note/task) has no `Message` to resolve via `getMessage()` below and is simply
143
- * dropped by the same eventually-consistent-index fallback that already existed, rather than rendered
144
- * (this inbox list only ever shows message rows; a real multi-entity-type results view is a separate,
145
- * larger UI project outside this pass). Shared by both the fresh-search orchestration and `loadMore()`
146
- * below, which each build this from the same `ParsedSearchQuery` differently only in `cursor`. */
147
- function tier1SearchParams(parsed: ParsedSearchQuery, cursor: string | undefined, mailboxUid: string) {
148
- return {
149
- // The mailbox actually open - omitted, the server searches the caller's *own* mailbox, which is the
150
- // wrong one whenever a shared mailbox's folder is being viewed.
151
- mailboxUid,
152
- types: parsed.entityTypes ?? ["message"],
153
- cursor,
154
- limit: MESSAGE_PAGE_SIZE,
155
- from: parsed.from,
156
- to: parsed.to,
157
- cc: parsed.cc,
158
- subject: parsed.subject,
159
- hasAttachment: parsed.hasAttachment,
160
- before: parsed.before,
161
- after: parsed.after,
162
- folderUid: parsed.folderUid,
163
- flags: parsed.flags,
164
- labels: parsed.labels,
165
- };
166
- }
167
-
168
- /** How many of Tier 1's own `metadataOnly` hits (§7: "an encrypted entity matched only on server-visible
169
- * metadata... MUST be rendered as skeleton entries in place... using the metadata score as a provisional
170
- * position") are shown as skeleton rows at once - §_Progressive Results_' "Skeletons MUST be capped, at
171
- * approximately one and a half pages." A non-`metadataOnly` Tier 1 hit (a real, already-scored content
172
- * match — always the case for unencrypted mail) is never a skeleton and is never subject to this cap.
173
- *
174
- * A Tier 3 candidate that Tier 1 did *not* already surface has no provisional score/position of its own
175
- * under the spec's own wording above, so it is deliberately never pre-rendered as a skeleton here either
176
- * - it simply appears, fully resolved, once Tier 3 confirms it (see `InboxContent`'s search
177
- * orchestration). */
178
- const SKELETON_CAP = Math.round(MESSAGE_PAGE_SIZE * 1.5);
179
-
180
- function capSkeletons(tier1Hits: SearchResult[]): SearchResult[] {
181
- let skeletonsSeen = 0;
182
- return tier1Hits.filter((hit) => {
183
- if (!hit.metadataOnly) {
184
- return true;
185
- }
186
- skeletonsSeen += 1;
187
- return skeletonsSeen <= SKELETON_CAP;
188
- });
189
- }
190
-
191
- /** How many candidates Tier 3 pulls per distinct search - larger than one page's worth so several
192
- * `loadMore()` pages can be sliced from one decrypt pass (see `Tier3Cache` below) instead of a second,
193
- * separately expensive server round trip and re-decrypt for the same query. Bounded, not unlimited - per
194
- * this module's own `tier1SearchParams()` sibling, Tier 3's own candidate-narrowing is already the
195
- * "heaviest single client-side cost" tier (`specs/search.md` §9's identical framing for attachment
196
- * extraction); a query whose true candidate set exceeds this simply pages out once this cache is
197
- * exhausted; `loadMore()` reflects that honestly via `hasMore`. */
198
- const TIER3_CANDIDATE_LIMIT = 200;
199
-
200
- /** One entry per distinct (mailbox, query, "search all mail" toggle, unlocked-or-not) combination this
201
- * tab has already run Tier 3 for - keyed by `tier3CacheKey()` below. Tier 3's decrypt-and-match pass
202
- * (`searchEncryptedCandidates()`) is by far this search's most expensive step, so it runs once per
203
- * combination; every subsequent `loadMore()` page for that same combination slices further into the
204
- * same already-decrypted array. Session-scoped, per tab, with no explicit eviction - a small map that's
205
- * simply never read again once the query changes, the same shape `InboxContent`'s own `decryptedRows`
206
- * state already accepts for a similar "worth keeping around, not worth actively pruning" tradeoff.
207
- *
208
- * The unlocked-or-not dimension matters: re-running an identical query right after an on-demand unlock
209
- * (`handleUnlockSearch()`) MUST NOT reuse the "nothing to contribute" entry that same query cached while
210
- * still locked - `searchEncryptedCandidates()` degrades to `[]` for an absent `unlocked`, and that empty
211
- * result is exactly as cacheable/reusable as a real one, just under a different key. */
212
- type Tier3Cache = Map<string, SearchResult[]>;
213
-
214
- /** Keyed by the exact query windows Tier 3 actually ran (`tier3Windows()` - which already reflect the query,
215
- * the "Search all mail" toggle, and Tier 2's coverage at the time), not just the query: the same query
216
- * narrowed differently (a build finished, new mail moved the coverage end) must not reuse a result that was
217
- * computed over a different date range. */
218
- function tier3CacheKey(mailboxUid: string, windows: ParsedSearchQuery[], unlocked: boolean): string {
219
- return `${mailboxUid}|${JSON.stringify(windows)}|${String(unlocked)}`;
220
- }
221
-
222
- /** A search query's cache/cursor identity - stable across re-parsing the identical raw text, and
223
- * distinct for anything else (§8's "a query fingerprint, so a cursor cannot be replayed against a
224
- * different query"). `JSON.stringify` on `ParsedSearchQuery` is deterministic here because every one of
225
- * its own fields is a primitive or a `Date` (which serializes to a fixed ISO string) - no nested object
226
- * whose key order could vary between two structurally-identical parses of the same text. */
227
- function queryFingerprint(parsed: ParsedSearchQuery): string {
228
- return JSON.stringify(parsed);
229
- }
230
-
231
- /** The date windows Tier 3 still has to search: the query's own range minus Tier 2's guaranteed coverage
232
- * `[coverage.indexedFrom, coverage.indexedUntil]`, unless the reader explicitly asked to "Search all mail".
233
- * Tier 2 already holds fully-decrypted, current content for that range, so re-fetching and re-decrypting it
234
- * through Tier 3's slower candidate-narrowing path would be pure waste. Yields up to two windows - older than
235
- * the coverage (`before:` tightened to `indexedFrom`) and newer than it (`after:` raised to `indexedUntil`,
236
- * since nothing indexes mail that arrived after the build pass started) - never *widening* a bound the query
237
- * already specified, and none at all when the query lies entirely inside the coverage.
238
- *
239
- * Only narrows once Tier 2 reports a finished, complete build pass from this session: while it's still
240
- * building (or a pass stopped early - a failed folder listing, the byte budget) `indexedFrom` is just the
241
- * oldest row that happens to be present, not a guarantee every encrypted message since then is indexed, and
242
- * narrowing on it would silently drop encrypted results neither tier returns. */
243
- function tier3Windows(parsed: ParsedSearchQuery, coverage: Coverage | undefined, searchAllMail: boolean): ParsedSearchQuery[] {
244
- if (searchAllMail || !coverage?.indexedFrom || !coverage.indexedUntil || coverage.building || !coverage.complete) {
245
- return [parsed];
246
- }
247
- const coveredFrom = new Date(coverage.indexedFrom);
248
- const coveredUntil = new Date(coverage.indexedUntil);
249
- const windows: ParsedSearchQuery[] = [];
250
- if (!parsed.after || parsed.after.getTime() < coveredFrom.getTime()) {
251
- windows.push({ ...parsed, before: parsed.before && parsed.before.getTime() < coveredFrom.getTime() ? parsed.before : coveredFrom });
252
- }
253
- if (!parsed.before || parsed.before.getTime() > coveredUntil.getTime()) {
254
- windows.push({ ...parsed, after: parsed.after && parsed.after.getTime() > coveredUntil.getTime() ? parsed.after : coveredUntil });
255
- }
256
- return windows;
257
- }
258
-
259
- /** Runs Tier 3 over each window and merges the candidates (a uid can't match in two disjoint windows, but a
260
- * message whose date sits exactly on a boundary may come back from both). */
261
- async function searchTier3Windows(windows: ParsedSearchQuery[], unlocked: UnlockedKeys | undefined, mailboxUid: string): Promise<SearchResult[]> {
262
- const pages = await Promise.all(
263
- windows.map((window) => searchEncryptedCandidates(window, unlocked, TIER3_CANDIDATE_LIMIT, { mailboxUid })),
264
- );
265
- const merged = new Map<string, SearchResult>();
266
- for (const result of pages.flat()) {
267
- if (!merged.has(result.entityUid)) {
268
- merged.set(result.entityUid, result);
269
- }
270
- }
271
- return [...merged.values()];
272
- }
273
-
274
- /** The paging state for one search, composited across all three tiers (`specs/search.md` §8) - opaque to
275
- * every caller the same way `SearchResultPage.nextCursor` is opaque to callers of `search()` itself.
276
- * Tier 1 keeps the server's own opaque cursor unmodified; Tier 2 (the local index) and Tier 3 (the
277
- * cached, already-decrypted candidate array - see `Tier3Cache` above) are both this client's own state,
278
- * so their "position" is just a plain offset into each. */
279
- interface CompositeCursor {
280
- tier1Cursor?: string;
281
- tier2Offset: number;
282
- tier3Offset: number;
283
- /** The `Tier3Cache` entry the first page was sliced from - later pages keep slicing the same one. */
284
- tier3Key: string;
285
- fingerprint: string;
286
- }
287
-
288
- /** `undefined` for a missing, corrupted, or foreign-query cursor - every caller already treats "no
289
- * cursor" as "start this tier from the beginning," so there's no separate error path needed here. */
290
- function decodeCursor(raw: CompositeCursor | undefined, fingerprint: string): CompositeCursor | undefined {
291
- return raw?.fingerprint === fingerprint ? raw : undefined;
292
- }
293
-
294
- /** Resolves every hit's `entityUid` to a full `Message` via `getMessage()`, reusing `cache` across
295
- * repeated calls within the same search pass - `InboxContent`'s own search orchestration below re-merges
296
- * and re-resolves the *entire* current hit set each time a tier resolves, so without this cache every
297
- * stage would re-fetch messages an earlier stage already fetched. A hit whose message no longer resolves
298
- * (deleted after being indexed, or the fetch itself failed) is cached as `null` and dropped - the same
299
- * "a search hit can briefly outlive the message it points to" tolerance this function's inline
300
- * predecessor already had. */
301
- async function resolveHitsToMessages(
302
- hits: SearchResult[],
303
- cache: Map<string, Message | null>,
304
- ): Promise<{ messages: Message[]; snippets: Record<string, string> }> {
305
- const toFetch = hits.filter((hit) => !cache.has(hit.entityUid));
306
- await Promise.all(
307
- toFetch.map(async (hit) => {
308
- const message = await getMessage(hit.entityUid).catch(() => null);
309
- cache.set(hit.entityUid, message);
310
- }),
311
- );
312
- const messages: Message[] = [];
313
- const snippets: Record<string, string> = {};
314
- for (const hit of hits) {
315
- const message = cache.get(hit.entityUid);
316
- if (!message) {
317
- continue;
318
- }
319
- messages.push(message);
320
- if (hit.snippet) {
321
- snippets[message.uid] = hit.snippet;
322
- }
323
- }
324
- return { messages, snippets };
325
- }
326
-
327
- /** How far outside the scroll container's visible area the load-more sentinel still counts as "in view". */
328
- const LOAD_MORE_ROOT_MARGIN_PX = 200;
329
-
330
- /** How many full pages in a row that added no new rows the list keeps loading on its own before it shows a
331
- * "Load more" button instead. */
332
- const MAX_EMPTY_PAGE_CONTINUATIONS = 3;
333
-
334
- /** `true` when `more` has at least one uid `shown` doesn't - i.e. appending it actually adds rows. */
335
- function hasUnseenMessages(shown: Message[], more: Message[]): boolean {
336
- const seen = new Set(shown.map((m) => m.uid));
337
- return more.some((m) => !seen.has(m.uid));
338
- }
339
-
340
- /** The load-more sentinel's actual current geometry against its scroll container, with the same margin the
341
- * IntersectionObserver uses. */
342
- function isWithinLoadMoreRange(sentinel: HTMLElement, root: HTMLElement): boolean {
343
- const rect = sentinel.getBoundingClientRect();
344
- const rootRect = root.getBoundingClientRect();
345
- return rect.top <= rootRect.bottom + LOAD_MORE_ROOT_MARGIN_PX && rect.bottom >= rootRect.top - LOAD_MORE_ROOT_MARGIN_PX;
346
- }
347
-
348
- /** Appends `more` to `shown`, skipping any uid already shown - a later page can repeat rows (Tier 1 and
349
- * Tier 2/3 cursors advance independently, so the same message can come back from a different tier on a
350
- * later page; a plain folder listing's pages shift when new mail arrives between fetches). */
351
- function appendUnseenMessages(shown: Message[], more: Message[]): Message[] {
352
- const seen = new Set(shown.map((m) => m.uid));
353
- const unseen: Message[] = [];
354
- for (const message of more) {
355
- if (!seen.has(message.uid)) {
356
- seen.add(message.uid);
357
- unseen.push(message);
358
- }
359
- }
360
- return unseen.length === 0 ? shown : [...shown, ...unseen];
361
- }
362
-
363
- /** Flattens and sorts a per-mailbox fetch into one merged, newest-first list - the aggregate ("All
364
- * Inboxes" etc.) equivalent of `mergeSearchResults()` above, but simpler: an aggregated message has no
365
- * natural relevance score to normalize, so this only ever sorts by `receivedDate`. */
366
- function mergeInboxMessages(perMailbox: { mailbox: Mailbox; messages: Message[] }[]): Message[] {
367
- return perMailbox
368
- .flatMap((entry) => entry.messages)
369
- .sort((a, b) => new Date(b.receivedDate).getTime() - new Date(a.receivedDate).getTime());
370
- }
371
-
372
- /**
373
- * Fans out one `listMessages()` call per accessible mailbox that has a folder of `type`, merges the
374
- * results newest-first. A mailbox with no matching folder, or whose fetch fails, simply contributes
375
- * nothing - one mailbox's absence/failure must not blank out every other mailbox's messages.
376
- *
377
- * **Pagination scope trim (deliberate, matching this file's own documented Tier 2/3 tradeoffs)**: there is
378
- * no composite cursor across an arbitrary number of independently-paginated mailboxes in this pass - this
379
- * always fetches exactly each mailbox's own first page (`MESSAGE_PAGE_SIZE`) and the caller never offers a
380
- * "load more" for the result (see `InboxContent`'s own `hasMore` handling in aggregate mode) - a real
381
- * composite-cursor "load more" per mailbox is a natural v2 if usage shows people scrolling past the first
382
- * page in aggregate view often.
383
- */
384
- async function fetchAggregateMessages(mailboxFolders: MailboxFolders[], type: AggregateFolderType): Promise<Message[]> {
385
- const perMailbox = await Promise.all(
386
- mailboxFolders.map(async ({ mailbox, folders }) => {
387
- const folder = folders.find((f) => f.type === type);
388
- if (!folder) {
389
- return { mailbox, messages: [] as Message[] };
390
- }
391
- const messages = await listMessages(folder.uid, { limit: MESSAGE_PAGE_SIZE }).catch(() => [] as Message[]);
392
- return { mailbox, messages };
393
- }),
394
- );
395
- return mergeInboxMessages(perMailbox);
396
- }
397
-
398
- export default function InboxPage(props: MailShellProps) {
399
- return (
400
- <MailShell {...props}>
401
- <InboxContent userUid={props.userUid} />
402
- </MailShell>
403
- );
404
- }
405
-
406
- function InboxContent({ userUid }: { userUid?: string }) {
407
- const { folderUid, mailboxUid, mailboxes, mailboxFolders, aggregateFolderType } = useMailShell();
408
- const isMobile = useIsMobile();
409
- const { requestUnlock } = useUnlockPrompt();
410
- const [viewMode, setViewMode] = useState<ViewMode>("date");
411
- const [messages, setMessages] = useState<Message[]>([]);
412
- const [conversations, setConversations] = useState<ConversationSummary[]>([]);
413
- const [loading, setLoading] = useState(true);
414
- const [loadingMore, setLoadingMore] = useState(false);
415
- const [hasMore, setHasMore] = useState(false);
416
- const [error, setError] = useState<string | null>(null);
417
- const [selectedUid, setSelectedUid] = useState<string | null>(null);
418
- const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);
419
- const [classificationFilter, setClassificationFilter] = useState<MessageClassification | "all">("all");
420
- const [searchInput, setSearchInput] = useState("");
421
- const [searchQuery, setSearchQuery] = useState("");
422
- const [snippets, setSnippets] = useState<Record<string, string>>({});
423
- const [labels, setLabels] = useState<Label[]>([]);
424
- // Tier 2's own reported window coverage for the current search - undefined outside a search, or
425
- // before Tier 2 has resolved yet for this search pass.
426
- const [coverage, setCoverage] = useState<Coverage | undefined>(undefined);
427
- // Keyed by message uid - see decryptEncryptedRows(). Never cleared on folder/search switches (a
428
- // decrypted row stays decrypted while its keys stay unlocked; re-decrypting on every navigation would
429
- // waste work for no benefit) - only cleared when the mailbox's keys are locked (see the
430
- // `subscribeKeySession()` effect below).
431
- const [decryptedRows, setDecryptedRows] = useState<Record<string, DecryptedRow>>({});
432
- // Bumped after a successful on-demand unlock to re-run the search effect below - it's not a
433
- // dependency the effect could otherwise react to (getUnlockedKeys() is a plain module-level read, not
434
- // React state; see keySession.ts's own doc comment).
435
- const [unlockRefresh, setUnlockRefresh] = useState(0);
436
- // §_Progressive Results_: which of the current search's uids are still an unconfirmed Tier 1
437
- // `metadataOnly` guess (rendered as a skeleton row - see the JSX below) - empty outside a search, and
438
- // always empty again once every tier has reported for the current pass (each unresolved entry is by
439
- // then either confirmed, real content, or pruned - see the search orchestration effect).
440
- const [pendingUids, setPendingUids] = useState<Set<string>>(new Set());
441
- // Withholds a hard result count until every tier has reported for the current search pass (§_Progressive
442
- // Results_: "Never show a hard count until every tier has reported... A settled count is the signal
443
- // that ordering is final"). Reset on every fresh search; irrelevant outside search mode.
444
- const [tier1Done, setTier1Done] = useState(false);
445
- const [tier2Done, setTier2Done] = useState(false);
446
- const [tier3Done, setTier3Done] = useState(false);
447
- // Toggled by the "Search all mail" action next to the results count - removes Tier 3's own default
448
- // bound (tightened to Tier 2's coverage window otherwise - see tightenBeforeToCoverage()) for one
449
- // re-run. Stored as the mailbox/folder/query it was requested for, not a plain flag, so it resets the
450
- // moment any of those change - derived in the same render, so the search effect never runs a new
451
- // query with a previous query's unbounded Tier 3 window first.
452
- const [searchAllMailKey, setSearchAllMailKey] = useState<string | null>(null);
453
- const searchAllMailScope = `${mailboxUid ?? ""}\n${folderUid ?? ""}\n${searchQuery}`;
454
- const searchAllMail = searchAllMailKey === searchAllMailScope;
455
- // Search stays real-folder-only - Tier 1/2/3 are all deeply mailbox/folder-scoped, and extending them
456
- // to span an arbitrary number of mailboxes is out of scope for this pass (see the aggregate-fetch
457
- // branch below, which the search effect never reaches while `folderUid` is unset).
458
- const isSearching = viewMode === "date" && searchQuery.length > 0 && !aggregateFolderType;
459
- // How far into the folder's *current* server-side listing the rows fetched so far reach. Offset
460
- // paging, not a cursor (`listMessages()` has none): a row removed locally (archived, scheduled send
461
- // cancelled) also left the folder server-side, shifting every later message back by one - so each
462
- // removal steps this back too, or the next page would silently skip a message. See `loadMore()`.
463
- const listedOffsetRef = useRef(0);
464
- const scrollContainerRef = useRef<HTMLDivElement | null>(null);
465
- // State (via a callback ref), not a plain ref: the sentinel mounts and unmounts as the list loads,
466
- // filters, and empties, and the observer effect below must re-attach to whichever node is current.
467
- const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
468
- const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
469
- const loadMoreErrorRef = useRef<string | null>(null);
470
- loadMoreErrorRef.current = loadMoreError;
471
- const loadMoreInFlightRef = useRef(false);
472
- // Bumped by `loadMore()` for each page that added at least one row - the only event the continuation
473
- // effect below keeps loading after. A counter rather than watching `loadingMore` flip back to false: a
474
- // fast response can settle before React ever renders the `true`, so that flip isn't reliably observable.
475
- const [appendedPageCount, setAppendedPageCount] = useState(0);
476
- // Consecutive full pages that added no new rows (every row was already shown - e.g. new mail shifted the
477
- // folder's pages). Such a page still counts as progress for the continuation effect, up to
478
- // `MAX_EMPTY_PAGE_CONTINUATIONS` in a row; past that, `loadMoreStalled` shows a "Load more" button
479
- // instead, so a server that keeps repeating rows is never looped on.
480
- const emptyPageStreakRef = useRef(0);
481
- const [loadMoreStalled, setLoadMoreStalled] = useState(false);
482
- const messagesRef = useRef(messages);
483
- messagesRef.current = messages;
484
- // The mailbox unlock/decrypt call sites below treat as "the" mailbox when there's no single selected
485
- // one (aggregate mode) - mirrors `MailShell`'s own identical `defaultMailboxUid` fallback. An
486
- // aggregate-view row from a *different*, not-yet-unlocked mailbox stays locked until that mailbox's
487
- // own folder view is opened directly - an accepted limitation, not a bug (see `MailShell`'s own doc
488
- // comment on the same tradeoff for its `LocalIndexLifecycle`/`KeyEnrollmentGate` wiring).
489
- const activeMailboxUid = mailboxUid ?? mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
490
- const mailboxKeys = mailboxes.find((mb) => mb.uid === activeMailboxUid)?.keys ?? [];
491
- // Reset to a fresh Map at the start of every new search pass (see the search effect below) - see
492
- // resolveHitsToMessages()'s own doc comment on why this needs to persist *within* one pass but not
493
- // across passes (a stale `null` for a uid that's since become resolvable elsewhere must not stick).
494
- const resolvedMessageCacheRef = useRef<Map<string, Message | null>>(new Map());
495
- // Session-scoped, never explicitly cleared - see Tier3Cache's own doc comment above.
496
- const tier3CacheRef = useRef<Tier3Cache>(new Map());
497
- // The latest composite cursor this search pass has reached - read by loadMore(), written at the end
498
- // of both the fresh-search orchestration and loadMore() itself. Not React state: it never drives a
499
- // render on its own, only what loadMore() does with it later.
500
- const compositeCursorRef = useRef<CompositeCursor | undefined>(undefined);
501
- // Guards every async load below - each search stage, the plain folder/conversation/aggregate listings,
502
- // and `loadMore()` - against a stale, still-in-flight pass clobbering state for a newer one that started
503
- // after it (the query, folder, or view changed) - the same `loadSeq`-style monotonic-id pattern already used elsewhere in this codebase (e.g.
504
- // `settings/privacy/index.tsx`'s `ExportSection`), generalized here across three independently-timed
505
- // async stages instead of one.
506
- const searchRunIdRef = useRef(0);
507
- // Bumped whenever `activeMailboxUid`'s keys are locked (see the `subscribeKeySession()` effect below) - a
508
- // decrypt that started before the lock checks it before storing its now-stale plaintext rows.
509
- const lockGenerationRef = useRef(0);
510
- // `messages` themselves aren't a dependency here on purpose - a message uid, once decrypted, is
511
- // never re-decrypted just because the list re-renders with the same rows (e.g. a folder-unrelated
512
- // state update elsewhere). New rows (a fresh page load, load-more, or a completed search) each
513
- // re-trigger this the normal way, by changing `messages` itself.
514
- //
515
- // Scoped to `activeMailboxUid`'s own rows only - in aggregate mode `messages` can span several
516
- // mailboxes, but only one mailbox's keys are ever being unlocked/tracked here (see `activeMailboxUid`'s
517
- // own doc comment above); an encrypted row from any other mailbox simply isn't a candidate for this
518
- // auto-decrypt or the manual unlock banner below.
519
- const undecryptedEncryptedUids = messages
520
- .filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && !decryptedRows[m.uid] && m.mailboxUid === activeMailboxUid)
521
- .map((m) => m.uid);
522
-
523
- // Once unlocked, silently decrypt this page's own encrypted rows to show their real subject/preview -
524
- // no prompt needed here, the same way searchEncryptedCandidates() already auto-includes decrypted
525
- // matches once unlocked without asking again. Only the *first* unlock (or a fresh page of messages
526
- // arriving) needs this; `handleUnlockList()` below covers the not-yet-unlocked case explicitly.
527
- useEffect(() => {
528
- if (undecryptedEncryptedUids.length === 0 || !activeMailboxUid) {
529
- return;
530
- }
531
- const unlocked = getUnlockedKeys(activeMailboxUid);
532
- if (!unlocked) {
533
- return;
534
- }
535
- let cancelled = false;
536
- const lockGeneration = lockGenerationRef.current;
537
- void decryptEncryptedRows(
538
- messages.filter((m) => undecryptedEncryptedUids.includes(m.uid)),
539
- unlocked,
540
- ).then((decrypted) => {
541
- // A lock while this was in flight already cleared `decryptedRows` - never put them back.
542
- if (!cancelled && lockGeneration === lockGenerationRef.current && Object.keys(decrypted).length > 0) {
543
- setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
544
- }
545
- });
546
- return () => {
547
- cancelled = true;
548
- };
549
- }, [messages, unlockRefresh]);
550
-
551
- // Locking a mailbox's keys (idle timeout, "Destroy keys on this device now", sign-out) must take its
552
- // decrypted content off screen too, not just out of memory: decrypted subjects/previews, search
553
- // snippets (Tier 2/3 snippets are decrypted content), and the already-decrypted Tier 3 candidates. A
554
- // live search re-runs, so Tier 2/3 contribute nothing again until the user unlocks. Read through a ref
555
- // so the subscription itself doesn't churn on every render.
556
- const keyLockStateRef = useRef({ activeMailboxUid, isSearching });
557
- keyLockStateRef.current = { activeMailboxUid, isSearching };
558
- useEffect(
559
- () =>
560
- subscribeKeySession(({ mailboxUid: changedMailboxUid, state }) => {
561
- const current = keyLockStateRef.current;
562
- if (state !== "locked" || changedMailboxUid !== current.activeMailboxUid) {
563
- return;
564
- }
565
- lockGenerationRef.current += 1;
566
- setDecryptedRows({});
567
- setSnippets({});
568
- tier3CacheRef.current.clear();
569
- if (current.isSearching) {
570
- setUnlockRefresh((n) => n + 1);
571
- }
572
- }),
573
- [],
574
- );
575
-
576
- async function handleUnlockList() {
577
- try {
578
- const unlocked = await requestUnlock(activeMailboxUid, mailboxKeys);
579
- const lockGeneration = lockGenerationRef.current;
580
- const decrypted = await decryptEncryptedRows(
581
- messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && m.mailboxUid === activeMailboxUid),
582
- unlocked,
583
- );
584
- if (lockGeneration === lockGenerationRef.current) {
585
- setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
586
- }
587
- } catch {
588
- // User dismissed the unlock dialog - rows stay exactly as they were.
589
- }
590
- }
591
-
592
- async function handleUnlockSearch() {
593
- try {
594
- await requestUnlock(activeMailboxUid, mailboxKeys);
595
- setUnlockRefresh((n) => n + 1);
596
- } catch {
597
- // User dismissed the unlock dialog - the search results stay exactly as they were.
598
- }
599
- }
600
-
601
- // Labels are mailbox-wide, not folder-scoped - fetched once per mailbox rather than per message, and
602
- // handed to the detail pane below. A failure here just means the Labels control stays hidden (an empty
603
- // `labels` array) rather than blocking the rest of the inbox. Keyed on the *selected message's own*
604
- // mailbox: aggregate views and search results can show messages from a mailbox other than
605
- // `activeMailboxUid`, and offering that mailbox's labels would let a label from the wrong mailbox be
606
- // applied. The conversation view stays scoped to `activeMailboxUid`, the mailbox its threads come from.
607
- const selectedMessageMailboxUid = messages.find((m) => m.uid === selectedUid)?.mailboxUid;
608
- const labelsMailboxUid = viewMode === "date" ? (selectedMessageMailboxUid ?? activeMailboxUid) : activeMailboxUid;
609
- // `labelsMailboxUid` is always set: `MailShell` only renders this component once at least one mailbox
610
- // exists, so `activeMailboxUid` (its fallback) always resolves.
611
- useEffect(() => {
612
- let cancelled = false;
613
- setLabels([]);
614
- listLabels(labelsMailboxUid, { limit: 200 })
615
- .then((result) => {
616
- if (!cancelled) {
617
- setLabels(result);
618
- }
619
- })
620
- .catch(() => undefined);
621
- return () => {
622
- cancelled = true;
623
- };
624
- }, [labelsMailboxUid]);
625
-
626
- // Debounce the raw input into the query actually searched, so every keystroke doesn't fire a request.
627
- useEffect(() => {
628
- const handle = setTimeout(() => setSearchQuery(searchInput.trim()), SEARCH_DEBOUNCE_MS);
629
- return () => clearTimeout(handle);
630
- }, [searchInput]);
631
-
632
- // Conversations are computed mailbox-wide (see `conversationsApi.ts`), not scoped to the selected
633
- // folder — switching into "By conversation" mode replaces the per-folder list entirely, and the
634
- // folder-tree sidebar's own selection becomes purely informational until switching back to "By date".
635
- useEffect(() => {
636
- setSelectedUid(null);
637
- setSelectedConversationId(null);
638
- setClassificationFilter("all");
639
- listedOffsetRef.current = 0;
640
- compositeCursorRef.current = undefined;
641
- setHasMore(false);
642
- setLoadMoreError(null);
643
- setLoadMoreStalled(false);
644
- emptyPageStreakRef.current = 0;
645
- // Every run - search or not - supersedes whatever an earlier run (or a `loadMore()` it started)
646
- // still has in flight; each async callback below checks this before touching state.
647
- searchRunIdRef.current += 1;
648
- const myRunId = searchRunIdRef.current;
649
- const isCurrentRun = () => searchRunIdRef.current === myRunId;
650
- // Also invalidates on unmount, so nothing lands after the component is gone. Unconditional: this
651
- // cleanup only ever runs for the latest run of this effect (React runs it before the next run
652
- // bumps the id, or on unmount), so the id is always still `myRunId` here.
653
- const invalidate = () => {
654
- searchRunIdRef.current += 1;
655
- };
656
-
657
- if (viewMode === "conversation") {
658
- // Conversations stay single-mailbox (not aggregated across mailboxes in this pass) - in
659
- // aggregate mode this falls back to `activeMailboxUid`, the same mailbox unlock/labels use
660
- // (always set - `MailShell` only renders this component once at least one mailbox exists).
661
- setLoading(true);
662
- setError(null);
663
- listConversations(activeMailboxUid)
664
- .then((result) => {
665
- if (isCurrentRun()) {
666
- setConversations(result);
667
- }
668
- })
669
- .catch((err) => {
670
- if (isCurrentRun()) {
671
- setError(err instanceof ApiRequestError ? err.message : "Could not load conversations.");
672
- }
673
- })
674
- .finally(() => {
675
- if (isCurrentRun()) {
676
- setLoading(false);
677
- }
678
- });
679
- return invalidate;
680
- }
681
-
682
- if (aggregateFolderType) {
683
- setLoading(true);
684
- setError(null);
685
- // hasMore stays false (set above) - see fetchAggregateMessages()'s own pagination scope trim.
686
- void fetchAggregateMessages(mailboxFolders, aggregateFolderType)
687
- .then((results) => {
688
- if (isCurrentRun()) {
689
- setMessages(results);
690
- }
691
- })
692
- .finally(() => {
693
- if (isCurrentRun()) {
694
- setLoading(false);
695
- }
696
- });
697
- return invalidate;
698
- }
699
-
700
- if (!folderUid) {
701
- setMessages([]);
702
- setLoading(false);
703
- return;
704
- }
705
- setLoading(true);
706
- setError(null);
707
-
708
- if (isSearching) {
709
- setCoverage(undefined);
710
- setPendingUids(new Set());
711
- setTier1Done(false);
712
- setTier2Done(false);
713
- setTier3Done(false);
714
- resolvedMessageCacheRef.current = new Map();
715
- const parsed = parseSearchQuery(searchQuery);
716
- const unlocked = getUnlockedKeys(mailboxUid!);
717
- const fingerprint = queryFingerprint(parsed);
718
-
719
- // Recomputes and re-renders the merged list from whatever tiers have reported so far -
720
- // called once after Tier 1+2 (interim: unconfirmed Tier 1 metadataOnly hits render as
721
- // skeletons) and again after Tier 3 (final: anything still unconfirmed is pruned instead -
722
- // §_Progressive Results_' "Skeletons resolve or disappear"). Bails out via `myRunId` if a
723
- // newer search pass has since started.
724
- async function reveal(tier1Hits: SearchResult[], tier2Hits: SearchResult[], tier3Hits: SearchResult[], final: boolean) {
725
- const capped = capSkeletons(tier1Hits);
726
- const confirmed = new Set([...tier2Hits, ...tier3Hits].map((r) => r.entityUid));
727
- const effectiveTier1 = final ? capped.filter((hit) => !hit.metadataOnly || confirmed.has(hit.entityUid)) : capped;
728
- const merged = mergeSearchResults(effectiveTier1, tier2Hits, tier3Hits);
729
- const { messages: resolved, snippets: resolvedSnippets } = await resolveHitsToMessages(
730
- merged,
731
- resolvedMessageCacheRef.current,
732
- );
733
- if (searchRunIdRef.current !== myRunId) {
734
- return;
735
- }
736
- setMessages(resolved);
737
- setSnippets(resolvedSnippets);
738
- if (final) {
739
- setPendingUids(new Set());
740
- } else {
741
- const pending = new Set<string>();
742
- for (const hit of capped) {
743
- if (hit.metadataOnly && !confirmed.has(hit.entityUid)) {
744
- pending.add(hit.entityUid);
745
- }
746
- }
747
- setPendingUids(pending);
748
- }
749
- }
750
-
751
- void (async () => {
752
- try {
753
- const [tier1Page, tier2Page] = await Promise.all([
754
- searchMailbox(parsed.text, tier1SearchParams(parsed, undefined, mailboxUid!)),
755
- searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, 0),
756
- ]);
757
- if (searchRunIdRef.current !== myRunId) {
758
- return;
759
- }
760
- setTier1Done(true);
761
- setTier2Done(true);
762
- setCoverage(tier2Page.coverage);
763
- setLoading(false);
764
- await reveal(tier1Page.results, tier2Page.results, [], false);
765
-
766
- const windows = tier3Windows(parsed, tier2Page.coverage, searchAllMail);
767
- const cacheKey = tier3CacheKey(mailboxUid!, windows, !!unlocked);
768
- let tier3Full = tier3CacheRef.current.get(cacheKey);
769
- if (!tier3Full) {
770
- tier3Full = await searchTier3Windows(windows, unlocked, mailboxUid!);
771
- if (searchRunIdRef.current !== myRunId) {
772
- return;
773
- }
774
- tier3CacheRef.current.set(cacheKey, tier3Full);
775
- }
776
- const tier3Page = tier3Full.slice(0, MESSAGE_PAGE_SIZE);
777
- setTier3Done(true);
778
- compositeCursorRef.current = {
779
- tier1Cursor: tier1Page.nextCursor,
780
- tier2Offset: tier2Page.results.length,
781
- tier3Offset: tier3Page.length,
782
- tier3Key: cacheKey,
783
- fingerprint,
784
- };
785
- setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || tier3Page.length < tier3Full.length);
786
- await reveal(tier1Page.results, tier2Page.results, tier3Page, true);
787
- } catch (err) {
788
- if (searchRunIdRef.current === myRunId) {
789
- setError(err instanceof ApiRequestError ? err.message : "Search failed.");
790
- setLoading(false);
791
- }
792
- }
793
- })();
794
- return invalidate;
795
- }
796
-
797
- listMessages(folderUid, { limit: MESSAGE_PAGE_SIZE })
798
- .then((results) => {
799
- if (isCurrentRun()) {
800
- setMessages(results);
801
- listedOffsetRef.current = results.length;
802
- setHasMore(results.length === MESSAGE_PAGE_SIZE);
803
- }
804
- })
805
- .catch((err) => {
806
- if (isCurrentRun()) {
807
- setError(err instanceof ApiRequestError ? err.message : "Could not load messages.");
808
- }
809
- })
810
- .finally(() => {
811
- if (isCurrentRun()) {
812
- setLoading(false);
813
- }
814
- });
815
- return invalidate;
816
- // `unlockRefresh`/`searchAllMail` are dependencies solely so `handleUnlockSearch()`/"Search all
817
- // mail" can force this effect to re-run the search above - Tier 3 (encrypted) results silently
818
- // contribute nothing without unlocked keys, so this is what actually makes them appear once the
819
- // user unlocks, and what makes "Search all mail" actually remove Tier 3's coverage bound. Neither
820
- // has any effect on the non-search branch below; re-running it with identical inputs just
821
- // re-fetches the same page.
822
- }, [viewMode, folderUid, mailboxUid, isSearching, searchQuery, unlockRefresh, searchAllMail, aggregateFolderType, mailboxFolders, activeMailboxUid]);
823
-
824
- function handleSearchAllMail() {
825
- setSearchAllMailKey(searchAllMailScope);
826
- }
827
-
828
- const loadMore = useCallback(async () => {
829
- const parsed = parseSearchQuery(searchQuery);
830
- const fingerprint = queryFingerprint(parsed);
831
- // While searching, a load-more continues from this query's own cursor - absent until its first page
832
- // has fully finished (the ref may still hold an earlier query's), in which case there's nowhere to
833
- // continue from yet.
834
- const searchCursor = decodeCursor(compositeCursorRef.current, fingerprint);
835
- if (
836
- loadMoreInFlightRef.current ||
837
- !hasMore ||
838
- loading ||
839
- viewMode !== "date" ||
840
- !folderUid ||
841
- (isSearching && !searchCursor)
842
- ) {
843
- return;
844
- }
845
- // A ref, not `loadingMore` state: the observer and the continuation effect below can both call in the
846
- // same tick, each closing over a render where `loadingMore` was still false.
847
- loadMoreInFlightRef.current = true;
848
- setLoadMoreError(null);
849
- setLoadMoreStalled(false);
850
- setLoadingMore(true);
851
- /** Records whether a landed page added rows, and whether the continuation effect should keep going. */
852
- const notePageLanded = (addedRows: boolean, moreRemain: boolean) => {
853
- if (addedRows) {
854
- emptyPageStreakRef.current = 0;
855
- setAppendedPageCount((n) => n + 1);
856
- } else if (moreRemain) {
857
- emptyPageStreakRef.current += 1;
858
- if (emptyPageStreakRef.current <= MAX_EMPTY_PAGE_CONTINUATIONS) {
859
- setAppendedPageCount((n) => n + 1);
860
- } else {
861
- emptyPageStreakRef.current = 0;
862
- setLoadMoreStalled(true);
863
- }
864
- }
865
- };
866
- // A query/folder/view change while this page is in flight bumps the run id (see the effect above) -
867
- // its rows then belong to a list that's no longer on screen and must not be appended to the new one.
868
- const myRunId = searchRunIdRef.current;
869
- const isCurrentRun = () => searchRunIdRef.current === myRunId;
870
- try {
871
- if (isSearching) {
872
- const unlocked = getUnlockedKeys(mailboxUid!);
873
- const cursor = searchCursor!;
874
-
875
- const [tier1Page, tier2Page] = await Promise.all([
876
- searchMailbox(parsed.text, tier1SearchParams(parsed, cursor.tier1Cursor, mailboxUid!)),
877
- searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, cursor.tier2Offset),
878
- ]);
879
- // The first page cached this pass under `tier3Key` before it created the cursor.
880
- const tier3Full = tier3CacheRef.current.get(cursor.tier3Key)!;
881
- const tier3Offset = cursor.tier3Offset;
882
- const tier3Page = tier3Full.slice(tier3Offset, tier3Offset + MESSAGE_PAGE_SIZE);
883
-
884
- // Unlike the fresh-search pass above, a load-more page is resolved and appended in one
885
- // shot rather than progressively revealed - rows already on screen shouldn't reorder or
886
- // grow skeletons out from under a reader who has since scrolled past them. Any Tier 1
887
- // metadataOnly hit this page that neither Tier 2 nor Tier 3 (both already awaited above)
888
- // confirms simply keeps showing its existing placeholder text rather than a live skeleton
889
- // - a deliberate, documented scope trim of progressive reveal to the first page only.
890
- const merged = mergeSearchResults(capSkeletons(tier1Page.results), tier2Page.results, tier3Page);
891
- const { messages: more, snippets: moreSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
892
- if (!isCurrentRun()) {
893
- return;
894
- }
895
- const addedRows = hasUnseenMessages(messagesRef.current, more);
896
- setMessages((prev) => appendUnseenMessages(prev, more));
897
- setSnippets((prev) => ({ ...prev, ...moreSnippets }));
898
-
899
- const nextTier3Offset = tier3Offset + tier3Page.length;
900
- compositeCursorRef.current = {
901
- tier1Cursor: tier1Page.nextCursor,
902
- tier2Offset: cursor.tier2Offset + tier2Page.results.length,
903
- tier3Offset: nextTier3Offset,
904
- tier3Key: cursor.tier3Key,
905
- fingerprint,
906
- };
907
- const moreRemain = !!tier1Page.nextCursor || tier2Page.hasMore || nextTier3Offset < tier3Full.length;
908
- setHasMore(moreRemain);
909
- notePageLanded(addedRows, moreRemain);
910
- } else {
911
- // The page containing the first message not fetched yet. After a local removal that offset is
912
- // no longer a page boundary, so this page overlaps rows already shown - `appendUnseenMessages()`
913
- // drops those - rather than skipping the message that shifted back across the boundary.
914
- const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
915
- const more = await listMessages(folderUid, { page, limit: MESSAGE_PAGE_SIZE });
916
- if (!isCurrentRun()) {
917
- return;
918
- }
919
- const addedRows = hasUnseenMessages(messagesRef.current, more);
920
- setMessages((prev) => appendUnseenMessages(prev, more));
921
- setHasMore(more.length === MESSAGE_PAGE_SIZE);
922
- listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
923
- notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
924
- }
925
- } catch (err) {
926
- // Shown next to the sentinel with a Retry button - never auto-retried (see the continuation
927
- // effect below), so a failing server isn't hammered while the sentinel stays in view.
928
- if (isCurrentRun()) {
929
- setLoadMoreError(err instanceof ApiRequestError ? err.message : "Could not load more messages.");
930
- }
931
- } finally {
932
- loadMoreInFlightRef.current = false;
933
- setLoadingMore(false);
934
- }
935
- }, [hasMore, loading, viewMode, folderUid, isSearching, searchQuery, mailboxUid]);
936
-
937
- // Always calls the latest `loadMore` closure so the effect below doesn't need `loadMore` itself in its
938
- // dependency array (it changes on every keystroke/page load, which would otherwise mean nothing here).
939
- const loadMoreRef = useRef(loadMore);
940
- loadMoreRef.current = loadMore;
941
-
942
- // Keyed on the sentinel node itself (see `sentinel`'s own comment): it unmounts whenever the list shows
943
- // "Loading..." and remounts afterwards, so an observer attached once to an earlier node would watch a
944
- // detached element forever. Only ever rendered in "By date" mode, so no view-mode check is needed.
945
- useEffect(() => {
946
- if (!sentinel) {
947
- return;
948
- }
949
- const observer = new IntersectionObserver(
950
- (entries) => {
951
- if (entries.some((entry) => entry.isIntersecting) && !loadMoreErrorRef.current) {
952
- void loadMoreRef.current();
953
- }
954
- },
955
- { root: scrollContainerRef.current, rootMargin: `${LOAD_MORE_ROOT_MARGIN_PX}px` },
956
- );
957
- observer.observe(sentinel);
958
- return () => observer.disconnect();
959
- }, [sentinel]);
960
-
961
- // An observer only reports *changes* - a sentinel still in view after a page lands (the new rows didn't
962
- // push it out of view, e.g. the Focused/Other filter hid every one of them) never reports again, so
963
- // keep loading while it's still in view. Only after a page that appended rows, or a full page of rows
964
- // already shown (bounded - see `emptyPageStreakRef`), never after a failure, and only when the sentinel's
965
- // real geometry says it's still in view (the observer's last report may predate the rows that just landed).
966
- useEffect(() => {
967
- if (appendedPageCount === 0) {
968
- return;
969
- }
970
- // The scroll container is always mounted whenever a sentinel is (the sentinel lives inside it).
971
- if (sentinel && isWithinLoadMoreRange(sentinel, scrollContainerRef.current!)) {
972
- void loadMoreRef.current();
973
- }
974
- }, [appendedPageCount]);
975
-
976
- function removeListedMessage(uid: string) {
977
- setMessages((prev) => prev.filter((m) => m.uid !== uid));
978
- listedOffsetRef.current = Math.max(0, listedOffsetRef.current - 1);
979
- setSelectedUid(null);
980
- }
981
-
982
- const selected = messages.find((m) => m.uid === selectedUid) ?? null;
983
- const selectedConversation = conversations.find((c) => c.conversationId === selectedConversationId) ?? null;
984
- const attachments = useMessageAttachments(selected);
985
- useMarkMessageRead(selected, (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))));
986
- // Search results can span every folder in the mailbox, not just the one selected in the sidebar - a
987
- // selected message's own folderUid is the only reliable source for its actual folder type once
988
- // searching (outside search, every message in `messages` already comes from `folderUid` itself, so
989
- // this falls back to the sidebar selection unchanged). Aggregate views span every *mailbox* too, so
990
- // the folder list consulted is the selected message's own mailbox's, not the shell's ambient one.
991
- const spansFolders = isSearching || !!aggregateFolderType;
992
- const selectedFolderUid = spansFolders ? (selected?.folderUid ?? folderUid) : folderUid;
993
- const selectedMailboxUid = spansFolders ? (selected?.mailboxUid ?? activeMailboxUid) : mailboxUid;
994
- const folders = mailboxFolders.find((mf) => mf.mailbox.uid === selectedMailboxUid)?.folders ?? [];
995
- const isSentItems = folders.find((f) => f.uid === selectedFolderUid)?.type === "sent_items";
996
- const isOutbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "outbox";
997
- const isInbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "inbox";
998
- const draftsFolderUid = folders.find((f) => f.type === "drafts")?.uid;
999
-
1000
- // Focused/Other is an Inbox-only concept (see `MessageDetailPane`'s own `isInbox` doc comment) — the
1001
- // sub-tabs only ever render there, so a message with no `inferenceClassification` (the common case:
1002
- // absent means Focused) or an explicit `"focused"` counts as Focused, everything else as Other. Not
1003
- // offered for an aggregate view (each mailbox classifies independently; merging that is out of scope).
1004
- const visibleMessages =
1005
- !isSearching && !aggregateFolderType && isInbox && classificationFilter !== "all"
1006
- ? messages.filter((m) =>
1007
- classificationFilter === "other"
1008
- ? m.inferenceClassification === "other"
1009
- : m.inferenceClassification !== "other",
1010
- )
1011
- : messages;
1012
-
1013
- const loadMoreStatus = loadingMore ? (
1014
- "Loading more…"
1015
- ) : loadMoreError ? (
1016
- <span className="inline-flex items-center gap-2">
1017
- <span role="alert" className="text-danger">
1018
- {loadMoreError}
1019
- </span>
1020
- <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1021
- Retry
1022
- </button>
1023
- </span>
1024
- ) : loadMoreStalled ? (
1025
- <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1026
- Load more
1027
- </button>
1028
- ) : null;
1029
-
1030
- function handleSelect(message: Message) {
1031
- if (isMobile) {
1032
- window.location.href = `/messages/${encodeURIComponent(message.uid)}`;
1033
- return;
1034
- }
1035
- setSelectedUid(message.uid);
1036
- }
1037
-
1038
- function handleSelectConversation(conversation: ConversationSummary) {
1039
- if (isMobile) {
1040
- // No dedicated mobile thread route yet — the existing single-message detail route already
1041
- // handles any message uid regardless of conversation grouping, so land on the most recent
1042
- // message in the thread rather than building a second mobile detail page for this phase.
1043
- // `messageUids` always has at least one entry — a `ConversationSummary` only ever exists
1044
- // because it was grouped from real messages (see `BaseMessageRoute.conversations()`).
1045
- const latestUid = conversation.messageUids[conversation.messageUids.length - 1];
1046
- window.location.href = `/messages/${encodeURIComponent(latestUid)}`;
1047
- return;
1048
- }
1049
- setSelectedConversationId(conversation.conversationId);
1050
- }
1051
-
1052
- if (!folderUid && !aggregateFolderType) {
1053
- // `MailShell` never renders this component at all until a mailbox is resolved (see its own
1054
- // full-screen `MailboxProvisioning` takeover otherwise) — this is purely the brief gap before
1055
- // that mailbox's own folder list has finished loading, not a "no mailbox" state. Distinct text
1056
- // from the message list's own "Loading…" below — otherwise the two transient states become
1057
- // indistinguishable to anything (a test, a user re-reading the screen) that catches this one.
1058
- return <p className="p-8 text-sm text-text-muted">Loading your mailbox&hellip;</p>;
1059
- }
1060
-
1061
- return (
1062
- <div className="flex h-full min-h-0">
1063
- <div ref={scrollContainerRef} className="w-full md:w-96 shrink-0 md:border-r border-border overflow-y-auto">
1064
- <div className="flex border-b border-border text-sm">
1065
- <button
1066
- type="button"
1067
- onClick={() => setViewMode("date")}
1068
- className={[
1069
- "flex-1 py-2 font-semibold",
1070
- viewMode === "date" ? "text-primary-dark border-b-2 border-primary-dark" : "text-text-muted",
1071
- ].join(" ")}
1072
- >
1073
- By date
1074
- </button>
1075
- <button
1076
- type="button"
1077
- onClick={() => setViewMode("conversation")}
1078
- className={[
1079
- "flex-1 py-2 font-semibold",
1080
- viewMode === "conversation" ? "text-primary-dark border-b-2 border-primary-dark" : "text-text-muted",
1081
- ].join(" ")}
1082
- >
1083
- By conversation
1084
- </button>
1085
- </div>
1086
- {viewMode === "conversation" && (
1087
- <p className="p-3 text-xs text-text-muted border-b border-border">
1088
- Showing every conversation in this mailbox — the selected folder doesn&apos;t filter this view.
1089
- </p>
1090
- )}
1091
- {viewMode === "date" && (
1092
- <div className="p-2 border-b border-border">
1093
- <input
1094
- type="search"
1095
- value={searchInput}
1096
- onChange={(e) => setSearchInput(e.target.value)}
1097
- placeholder={aggregateFolderType ? "Open a mailbox's own folder to search" : "Search all mail…"}
1098
- aria-label="Search all mail"
1099
- disabled={!!aggregateFolderType}
1100
- className="w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface disabled:opacity-55"
1101
- />
1102
- </div>
1103
- )}
1104
- {viewMode === "date" && isInbox && !isSearching && !aggregateFolderType && (
1105
- <div className="flex border-b border-border text-xs">
1106
- {(["all", "focused", "other"] as const).map((value) => (
1107
- <button
1108
- key={value}
1109
- type="button"
1110
- onClick={() => setClassificationFilter(value)}
1111
- className={[
1112
- "flex-1 py-1.5 font-semibold",
1113
- classificationFilter === value
1114
- ? "text-primary-dark border-b-2 border-primary-dark"
1115
- : "text-text-muted",
1116
- ].join(" ")}
1117
- >
1118
- {value === "all" ? "All" : value === "focused" ? "Focused" : "Other"}
1119
- </button>
1120
- ))}
1121
- </div>
1122
- )}
1123
-
1124
- {isSearching && (
1125
- <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border flex items-center justify-between gap-2">
1126
- {/* §_Progressive Results_: "Never show a hard count until every tier has reported.
1127
- Display n of ??, or omit the count. A settled count is the signal that ordering
1128
- is final." */}
1129
- <span>
1130
- {tier1Done && tier2Done && tier3Done
1131
- ? `${visibleMessages.length} result${visibleMessages.length === 1 ? "" : "s"}`
1132
- : `${visibleMessages.length} of ??`}
1133
- </span>
1134
- {tier2Done && !searchAllMail && (
1135
- <button
1136
- type="button"
1137
- onClick={handleSearchAllMail}
1138
- className="text-primary-dark hover:underline font-medium shrink-0"
1139
- >
1140
- Search all mail
1141
- </button>
1142
- )}
1143
- </div>
1144
- )}
1145
- {isSearching && coverage?.indexedFrom && (
1146
- <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border">
1147
- Local search covers messages back to {new Date(coverage.indexedFrom).toLocaleDateString()}
1148
- {coverage.building ? " (still building)" : ""}
1149
- {searchAllMail
1150
- ? " - searching everything, not just recent mail."
1151
- : " - older encrypted mail is still searched, just slower."}
1152
- </div>
1153
- )}
1154
- {isSearching && !getUnlockedKeys(mailboxUid!) && (
1155
- <div className="px-4 py-2 border-b border-border bg-surface-alt">
1156
- <button
1157
- type="button"
1158
- onClick={handleUnlockSearch}
1159
- className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1160
- >
1161
- <HiOutlineLockClosed size={12} aria-hidden="true" />
1162
- Unlock to include encrypted messages in these results
1163
- </button>
1164
- </div>
1165
- )}
1166
- {!isSearching && viewMode === "date" && undecryptedEncryptedUids.length > 0 && !getUnlockedKeys(activeMailboxUid) && (
1167
- <div className="px-4 py-2 border-b border-border bg-surface-alt">
1168
- <button
1169
- type="button"
1170
- onClick={handleUnlockList}
1171
- className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1172
- >
1173
- <HiOutlineLockClosed size={12} aria-hidden="true" />
1174
- Unlock to show {undecryptedEncryptedUids.length === 1 ? "an encrypted message's" : "encrypted messages'"} subject
1175
- </button>
1176
- </div>
1177
- )}
1178
-
1179
- {error && (
1180
- <div className="p-4">
1181
- <Alert>{error}</Alert>
1182
- </div>
1183
- )}
1184
-
1185
- {loading ? (
1186
- <p className="p-4 text-sm text-text-muted">Loading&hellip;</p>
1187
- ) : viewMode === "conversation" ? (
1188
- <ConversationList
1189
- conversations={conversations}
1190
- selectedId={selectedConversationId}
1191
- onSelect={handleSelectConversation}
1192
- />
1193
- ) : visibleMessages.length === 0 ? (
1194
- <>
1195
- <p className="p-4 text-sm text-text-muted">
1196
- {isSearching
1197
- ? `No messages match "${searchQuery}".`
1198
- : classificationFilter === "all"
1199
- ? "No messages in this folder."
1200
- : "No messages here."}
1201
- </p>
1202
- {/* Still offered while a filter hides every loaded row - what it's looking for may be
1203
- on a later page. */}
1204
- {hasMore && (
1205
- <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1206
- {loadMoreStatus}
1207
- </div>
1208
- )}
1209
- </>
1210
- ) : (
1211
- <>
1212
- <ul>
1213
- {visibleMessages.map((message) => (
1214
- <li key={message.uid}>
1215
- <button
1216
- type="button"
1217
- onClick={() => handleSelect(message)}
1218
- className={[
1219
- "w-full text-left px-4 py-3 border-b border-border",
1220
- message.uid === selectedUid ? "bg-primary/10" : "hover:bg-surface-alt",
1221
- message.flags.read ? "" : "font-semibold",
1222
- ].join(" ")}
1223
- >
1224
- <div className="flex items-center justify-between gap-2 text-sm">
1225
- <span className="truncate">{message.from.displayName || message.from.address}</span>
1226
- <span className="text-xs text-text-muted shrink-0">
1227
- {new Date(message.receivedDate).toLocaleDateString()}
1228
- </span>
1229
- </div>
1230
- {aggregateFolderType && (
1231
- // The one view where a row needs to say which mailbox it came from.
1232
- <div className="text-xs text-text-muted truncate font-normal">
1233
- {mailboxes.find((mb) => mb.uid === message.mailboxUid)?.displayName}
1234
- </div>
1235
- )}
1236
- {isSearching && pendingUids.has(message.uid) ? (
1237
- // §_Progressive Results_: "Unresolved encrypted results MUST
1238
- // be rendered as skeleton entries in place, not appended on
1239
- // arrival." This uid is a Tier 1 metadataOnly guess Tier 2/3
1240
- // haven't confirmed (or ruled out) yet.
1241
- <div className="flex flex-col gap-1.5 py-0.5">
1242
- <Skeleton height="h-3.5" className="w-2/3 rounded-sm" />
1243
- <Skeleton height="h-3" className="w-full rounded-sm" />
1244
- </div>
1245
- ) : (
1246
- <>
1247
- <div className="text-sm truncate">
1248
- {decryptedRows[message.uid]?.subject ||
1249
- (message.subject === ENCRYPTED_SUBJECT_PLACEHOLDER
1250
- ? "Encrypted message"
1251
- : message.subject) ||
1252
- "(no subject)"}
1253
- </div>
1254
- <div className="text-xs text-text-muted truncate font-normal">
1255
- {snippets[message.uid] || decryptedRows[message.uid]?.preview || message.bodyPreview}
1256
- </div>
1257
- </>
1258
- )}
1259
- </button>
1260
- </li>
1261
- ))}
1262
- </ul>
1263
- {hasMore && (
1264
- <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1265
- {loadMoreStatus}
1266
- </div>
1267
- )}
1268
- {aggregateFolderType && (
1269
- <p className="p-4 text-center text-xs text-text-muted">
1270
- Showing the most recent mail from each mailbox. Open a specific mailbox&rsquo;s folder to
1271
- see older mail.
1272
- </p>
1273
- )}
1274
- </>
1275
- )}
1276
- </div>
1277
- <div className="hidden md:flex flex-1 min-w-0">
1278
- {viewMode === "conversation" ? (
1279
- <ConversationThreadPane
1280
- conversation={selectedConversation}
1281
- folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
1282
- labels={labels}
1283
- />
1284
- ) : (
1285
- <MessageDetailPane
1286
- message={selected}
1287
- attachments={attachments}
1288
- isSentItems={isSentItems}
1289
- onRecalled={(updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)))}
1290
- isOutbox={isOutbox}
1291
- isInbox={isInbox}
1292
- onClassified={(updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)))}
1293
- onReceiptHandled={(updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)))}
1294
- draftsFolderUid={draftsFolderUid}
1295
- onScheduledSendCanceled={(updated) => {
1296
- // The message moved out of the currently-viewed Outbox folder (into Drafts)
1297
- // — unlike a recall, which patches a message in place, this removes it from
1298
- // the list entirely, matching what a real folder switch would show.
1299
- removeListedMessage(updated.uid);
1300
- }}
1301
- onArchived={(updated) => {
1302
- // Same reasoning as onScheduledSendCanceled above — the message moved out of
1303
- // whichever folder is currently being viewed (into Archive), so it's removed
1304
- // from the list rather than patched in place.
1305
- removeListedMessage(updated.uid);
1306
- }}
1307
- labels={labels}
1308
- onLabelsChanged={(updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)))}
1309
- />
1310
- )}
1311
- </div>
1312
- </div>
1313
- );
1314
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { useCallback, useEffect, useRef, useState } from "react";
6
+ import { HiOutlineFlag, HiOutlineLockClosed, HiOutlinePaperClip } from "react-icons/hi2";
7
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
+ import {
9
+ Folder,
10
+ Mailbox,
11
+ Message,
12
+ MessageListFilter,
13
+ MessageListParams,
14
+ archiveMessage,
15
+ bulkUpdateMessages,
16
+ createFolder,
17
+ getMessage,
18
+ getMessageRawContent,
19
+ listMessages,
20
+ moveMessages,
21
+ setMessagesFlagged,
22
+ setMessagesRead,
23
+ } from "@rapidmx/react-shared/mail/mailApi.js";
24
+ import { Label, listLabels } from "@rapidmx/react-shared/mail/labelsApi.js";
25
+ import {
26
+ ConversationListParams,
27
+ ConversationSummary,
28
+ listConversationMessages,
29
+ listConversations,
30
+ } from "@rapidmx/react-shared/mail/conversationsApi.js";
31
+ import { SearchResult, search as searchMailbox } from "@rapidmx/react-shared/search/searchApi.js";
32
+ import { parseSearchQuery, type ParsedSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
33
+ import { normalizeServerScores } from "@rapidmx/react-shared/search/searchScoring.js";
34
+ import { searchEncryptedCandidates } from "@rapidmx/react-shared/search/searchTier3.js";
35
+ import { searchLocalIndex } from "../shared/search/searchTier2.js";
36
+ import type { Coverage } from "../shared/search/localIndexWorker.js";
37
+ import { getUnlockedKeys, subscribeKeySession, UnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
38
+ import { evaluateMessageSecurity } from "@rapidmx/react-shared/crypto/messageSecurity.js";
39
+ import { useMarkMessageRead, useMessageAttachments } from "@rapidmx/react-shared/mail/mailDetailHooks.js";
40
+ import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
41
+ import MailShell, {
42
+ AggregateFolderType,
43
+ MailboxFolders,
44
+ MailShellProps,
45
+ useMailShell,
46
+ } from "../shared/components/mail/layout/MailShell.js";
47
+ import MessageDetailPane from "../shared/components/mail/MessageDetailPane.js";
48
+ import ConversationList from "../shared/components/mail/ConversationList.js";
49
+ import ConversationThreadPane from "../shared/components/mail/ConversationThreadPane.js";
50
+ import MailListToolbar from "../shared/components/mail/MailListToolbar.js";
51
+ import MailSelectionBar from "../shared/components/mail/MailSelectionBar.js";
52
+ import {
53
+ CONVERSATION_SORT_NOTE,
54
+ CONVERSATION_SORT_UNAVAILABLE,
55
+ MAIL_LIST_CLASSIFICATION_FILTERS,
56
+ MailListPreferences,
57
+ getMailListPreferences,
58
+ setMailListPreferences,
59
+ sortConversations,
60
+ } from "../shared/components/mail/listPreferences.js";
61
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
62
+ import Skeleton from "@rapidmx/react-shared/components/feedback/Skeleton.js";
63
+ import { useUnlockPrompt } from "../shared/components/layout/UnlockPromptProvider.js";
64
+
65
+ const MESSAGE_PAGE_SIZE = 50;
66
+ const SEARCH_DEBOUNCE_MS = 300;
67
+ const LIST_PREVIEW_MAX_LENGTH = 160;
68
+
69
+ /** The literal outer-envelope `Subject` every encrypted message carries server-side - RFC 9788's
70
+ * `hcp_baseline` policy obscures it to this exact string (see `smimeMessage.ts`'s
71
+ * `applyBaselineOuterHeaders()`), which is also all `Message.subject` ever shows for one of these until
72
+ * decrypted client-side. Used here to recognize which loaded rows are worth decrypting for display. */
73
+ const ENCRYPTED_SUBJECT_PLACEHOLDER = "[...]";
74
+
75
+ /** A row's client-recovered subject/preview, once decrypted - `undefined` fields mean nothing better
76
+ * than the placeholder/blank server value was recoverable for that field specifically. */
77
+ interface DecryptedRow {
78
+ subject?: string;
79
+ preview?: string;
80
+ }
81
+
82
+ /** Strips HTML down to plain text, for a short list-row preview of a decrypted body - mirrors
83
+ * `searchTier3.ts`'s own private `stripHtml()` (not currently exported from `@rapidmx/react-shared`,
84
+ * so duplicated here rather than pulled in through a package change just for this one small, pure
85
+ * helper). Not a security boundary - the output only ever feeds plain text display, truncated below,
86
+ * never rendered back into any DOM. */
87
+ function stripHtmlToText(html: string): string {
88
+ return html
89
+ .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ")
90
+ .replace(/<[^>]+>/g, " ")
91
+ .replace(/&nbsp;/gi, " ")
92
+ .replace(/&amp;/gi, "&")
93
+ .replace(/&lt;/gi, "<")
94
+ .replace(/&gt;/gi, ">")
95
+ .replace(/&quot;/gi, '"')
96
+ .replace(/&#0*39;/gi, "'")
97
+ .replace(/\s+/g, " ")
98
+ .trim();
99
+ }
100
+
101
+ /**
102
+ * Decrypts the subject/preview of every currently-loaded row whose subject is still the RFC 9788
103
+ * placeholder (i.e. every encrypted message this device hasn't already resolved), keyed by uid - the
104
+ * inbox-list counterpart to `MessageDetailPane`'s own single-message decrypt and `searchTier3.ts`'s
105
+ * per-candidate decrypt. Bounded to `messages` (at most one loaded page, `MESSAGE_PAGE_SIZE`), never the
106
+ * whole mailbox - matching `searchEncryptedCandidates()`'s own "bounded, not everything" scope. Runs only
107
+ * once `unlocked` is available (the caller decides when to call this - see `InboxContent`'s own effect
108
+ * and `handleUnlockList()`), and a single row's fetch/decrypt failure never blocks the rest.
109
+ */
110
+ async function decryptEncryptedRows(messages: Message[], unlocked: UnlockedKeys): Promise<Record<string, DecryptedRow>> {
111
+ const encrypted = messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER);
112
+ const entries = await Promise.all(
113
+ encrypted.map(async (message): Promise<[string, DecryptedRow] | null> => {
114
+ try {
115
+ const rawMime = await getMessageRawContent(message.uid);
116
+ const security = await evaluateMessageSecurity(rawMime, unlocked);
117
+ if (!security.subject && !security.html) {
118
+ return null;
119
+ }
120
+ const preview = security.html ? stripHtmlToText(security.html).slice(0, LIST_PREVIEW_MAX_LENGTH) : undefined;
121
+ return [message.uid, { subject: security.subject, preview }];
122
+ } catch {
123
+ return null;
124
+ }
125
+ }),
126
+ );
127
+ const result: Record<string, DecryptedRow> = {};
128
+ for (const entry of entries) {
129
+ if (entry) {
130
+ result[entry[0]] = entry[1];
131
+ }
132
+ }
133
+ return result;
134
+ }
135
+
136
+ /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message), Tier 2 (local index, fully
137
+ * decrypted and re-scored), and Tier 3 (server-narrowed candidates, decrypted and re-scored) results into
138
+ * one ranked list, per `specs/search.md` §7's "client MUST re-score all results it can see... normalise
139
+ * into the same space rather than interleaving raw scores": each tier is normalized independently via
140
+ * `normalizeServerScores()` before merging, since a Postgres/OpenSearch score, a local `bm25()` score,
141
+ * and this module's own Tier 3 term-count score all occupy unrelated ranges. A uid present in more than
142
+ * one list keeps only the last-inserted entry (Tier 2 wins over Tier 3 wins over Tier 1) - Tier 2 and
143
+ * Tier 3 both represent genuine, content-verified scores for the same message, so which one "wins" on
144
+ * overlap doesn't change correctness, only which of two equally-valid scores is shown; either supersedes
145
+ * Tier 1's metadata-only guess for the same uid.
146
+ *
147
+ * Called progressively - once per tier as it resolves, each time with whatever tiers have reported so
148
+ * far (an empty array for the rest) - by `InboxContent`'s own search orchestration below, per §_Progressive
149
+ * Results_' "reordering is permitted and preferred over appending." This function itself stays pure and
150
+ * stateless; it has no notion of "in progress" versus "final." */
151
+ function mergeSearchResults(tier1: SearchResult[], tier2: SearchResult[], tier3: SearchResult[]): SearchResult[] {
152
+ const normalizedTier1 = normalizeServerScores(tier1);
153
+ const normalizedTier2 = normalizeServerScores(tier2);
154
+ const normalizedTier3 = normalizeServerScores(tier3);
155
+ const merged = new Map<string, { result: SearchResult; normalizedScore: number }>();
156
+ for (const entry of normalizedTier1) {
157
+ merged.set(entry.result.entityUid, entry);
158
+ }
159
+ for (const entry of normalizedTier3) {
160
+ merged.set(entry.result.entityUid, entry);
161
+ }
162
+ for (const entry of normalizedTier2) {
163
+ merged.set(entry.result.entityUid, entry);
164
+ }
165
+ return Array.from(merged.values())
166
+ .sort((a, b) => b.normalizedScore - a.normalizedScore)
167
+ .map((entry) => entry.result);
168
+ }
169
+
170
+ /** `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
171
+ * (contact/calendarEvent/note/task) has no `Message` to resolve via `getMessage()` below and is simply
172
+ * dropped by the same eventually-consistent-index fallback that already existed, rather than rendered
173
+ * (this inbox list only ever shows message rows; a real multi-entity-type results view is a separate,
174
+ * larger UI project outside this pass). Shared by both the fresh-search orchestration and `loadMore()`
175
+ * below, which each build this from the same `ParsedSearchQuery` differently only in `cursor`. */
176
+ function tier1SearchParams(parsed: ParsedSearchQuery, cursor: string | undefined, mailboxUid: string) {
177
+ return {
178
+ // The mailbox actually open - omitted, the server searches the caller's *own* mailbox, which is the
179
+ // wrong one whenever a shared mailbox's folder is being viewed.
180
+ mailboxUid,
181
+ types: parsed.entityTypes ?? ["message"],
182
+ cursor,
183
+ limit: MESSAGE_PAGE_SIZE,
184
+ from: parsed.from,
185
+ to: parsed.to,
186
+ cc: parsed.cc,
187
+ subject: parsed.subject,
188
+ hasAttachment: parsed.hasAttachment,
189
+ before: parsed.before,
190
+ after: parsed.after,
191
+ folderUid: parsed.folderUid,
192
+ flags: parsed.flags,
193
+ labels: parsed.labels,
194
+ };
195
+ }
196
+
197
+ /** How many of Tier 1's own `metadataOnly` hits (§7: "an encrypted entity matched only on server-visible
198
+ * metadata... MUST be rendered as skeleton entries in place... using the metadata score as a provisional
199
+ * position") are shown as skeleton rows at once - §_Progressive Results_' "Skeletons MUST be capped, at
200
+ * approximately one and a half pages." A non-`metadataOnly` Tier 1 hit (a real, already-scored content
201
+ * match — always the case for unencrypted mail) is never a skeleton and is never subject to this cap.
202
+ *
203
+ * A Tier 3 candidate that Tier 1 did *not* already surface has no provisional score/position of its own
204
+ * under the spec's own wording above, so it is deliberately never pre-rendered as a skeleton here either
205
+ * - it simply appears, fully resolved, once Tier 3 confirms it (see `InboxContent`'s search
206
+ * orchestration). */
207
+ const SKELETON_CAP = Math.round(MESSAGE_PAGE_SIZE * 1.5);
208
+
209
+ function capSkeletons(tier1Hits: SearchResult[]): SearchResult[] {
210
+ let skeletonsSeen = 0;
211
+ return tier1Hits.filter((hit) => {
212
+ if (!hit.metadataOnly) {
213
+ return true;
214
+ }
215
+ skeletonsSeen += 1;
216
+ return skeletonsSeen <= SKELETON_CAP;
217
+ });
218
+ }
219
+
220
+ /** How many candidates Tier 3 pulls per distinct search - larger than one page's worth so several
221
+ * `loadMore()` pages can be sliced from one decrypt pass (see `Tier3Cache` below) instead of a second,
222
+ * separately expensive server round trip and re-decrypt for the same query. Bounded, not unlimited - per
223
+ * this module's own `tier1SearchParams()` sibling, Tier 3's own candidate-narrowing is already the
224
+ * "heaviest single client-side cost" tier (`specs/search.md` §9's identical framing for attachment
225
+ * extraction); a query whose true candidate set exceeds this simply pages out once this cache is
226
+ * exhausted; `loadMore()` reflects that honestly via `hasMore`. */
227
+ const TIER3_CANDIDATE_LIMIT = 200;
228
+
229
+ /** One entry per distinct (mailbox, query, "search all mail" toggle, unlocked-or-not) combination this
230
+ * tab has already run Tier 3 for - keyed by `tier3CacheKey()` below. Tier 3's decrypt-and-match pass
231
+ * (`searchEncryptedCandidates()`) is by far this search's most expensive step, so it runs once per
232
+ * combination; every subsequent `loadMore()` page for that same combination slices further into the
233
+ * same already-decrypted array. Session-scoped, per tab, with no explicit eviction - a small map that's
234
+ * simply never read again once the query changes, the same shape `InboxContent`'s own `decryptedRows`
235
+ * state already accepts for a similar "worth keeping around, not worth actively pruning" tradeoff.
236
+ *
237
+ * The unlocked-or-not dimension matters: re-running an identical query right after an on-demand unlock
238
+ * (`handleUnlockSearch()`) MUST NOT reuse the "nothing to contribute" entry that same query cached while
239
+ * still locked - `searchEncryptedCandidates()` degrades to `[]` for an absent `unlocked`, and that empty
240
+ * result is exactly as cacheable/reusable as a real one, just under a different key. */
241
+ type Tier3Cache = Map<string, SearchResult[]>;
242
+
243
+ /** Keyed by the exact query windows Tier 3 actually ran (`tier3Windows()` - which already reflect the query,
244
+ * the "Search all mail" toggle, and Tier 2's coverage at the time), not just the query: the same query
245
+ * narrowed differently (a build finished, new mail moved the coverage end) must not reuse a result that was
246
+ * computed over a different date range. */
247
+ function tier3CacheKey(mailboxUid: string, windows: ParsedSearchQuery[], unlocked: boolean): string {
248
+ return `${mailboxUid}|${JSON.stringify(windows)}|${String(unlocked)}`;
249
+ }
250
+
251
+ /** A search query's cache/cursor identity - stable across re-parsing the identical raw text, and
252
+ * distinct for anything else (§8's "a query fingerprint, so a cursor cannot be replayed against a
253
+ * different query"). `JSON.stringify` on `ParsedSearchQuery` is deterministic here because every one of
254
+ * its own fields is a primitive or a `Date` (which serializes to a fixed ISO string) - no nested object
255
+ * whose key order could vary between two structurally-identical parses of the same text. */
256
+ function queryFingerprint(parsed: ParsedSearchQuery): string {
257
+ return JSON.stringify(parsed);
258
+ }
259
+
260
+ /** The date windows Tier 3 still has to search: the query's own range minus Tier 2's guaranteed coverage
261
+ * `[coverage.indexedFrom, coverage.indexedUntil]`, unless the reader explicitly asked to "Search all mail".
262
+ * Tier 2 already holds fully-decrypted, current content for that range, so re-fetching and re-decrypting it
263
+ * through Tier 3's slower candidate-narrowing path would be pure waste. Yields up to two windows - older than
264
+ * the coverage (`before:` tightened to `indexedFrom`) and newer than it (`after:` raised to `indexedUntil`,
265
+ * since nothing indexes mail that arrived after the build pass started) - never *widening* a bound the query
266
+ * already specified, and none at all when the query lies entirely inside the coverage.
267
+ *
268
+ * Only narrows once Tier 2 reports a finished, complete build pass from this session: while it's still
269
+ * building (or a pass stopped early - a failed folder listing, the byte budget) `indexedFrom` is just the
270
+ * oldest row that happens to be present, not a guarantee every encrypted message since then is indexed, and
271
+ * narrowing on it would silently drop encrypted results neither tier returns. */
272
+ function tier3Windows(parsed: ParsedSearchQuery, coverage: Coverage | undefined, searchAllMail: boolean): ParsedSearchQuery[] {
273
+ if (searchAllMail || !coverage?.indexedFrom || !coverage.indexedUntil || coverage.building || !coverage.complete) {
274
+ return [parsed];
275
+ }
276
+ const coveredFrom = new Date(coverage.indexedFrom);
277
+ const coveredUntil = new Date(coverage.indexedUntil);
278
+ const windows: ParsedSearchQuery[] = [];
279
+ if (!parsed.after || parsed.after.getTime() < coveredFrom.getTime()) {
280
+ windows.push({ ...parsed, before: parsed.before && parsed.before.getTime() < coveredFrom.getTime() ? parsed.before : coveredFrom });
281
+ }
282
+ if (!parsed.before || parsed.before.getTime() > coveredUntil.getTime()) {
283
+ windows.push({ ...parsed, after: parsed.after && parsed.after.getTime() > coveredUntil.getTime() ? parsed.after : coveredUntil });
284
+ }
285
+ return windows;
286
+ }
287
+
288
+ /** Runs Tier 3 over each window and merges the candidates (a uid can't match in two disjoint windows, but a
289
+ * message whose date sits exactly on a boundary may come back from both). */
290
+ async function searchTier3Windows(windows: ParsedSearchQuery[], unlocked: UnlockedKeys | undefined, mailboxUid: string): Promise<SearchResult[]> {
291
+ const pages = await Promise.all(
292
+ windows.map((window) => searchEncryptedCandidates(window, unlocked, TIER3_CANDIDATE_LIMIT, { mailboxUid })),
293
+ );
294
+ const merged = new Map<string, SearchResult>();
295
+ for (const result of pages.flat()) {
296
+ if (!merged.has(result.entityUid)) {
297
+ merged.set(result.entityUid, result);
298
+ }
299
+ }
300
+ return [...merged.values()];
301
+ }
302
+
303
+ /** The paging state for one search, composited across all three tiers (`specs/search.md` §8) - opaque to
304
+ * every caller the same way `SearchResultPage.nextCursor` is opaque to callers of `search()` itself.
305
+ * Tier 1 keeps the server's own opaque cursor unmodified; Tier 2 (the local index) and Tier 3 (the
306
+ * cached, already-decrypted candidate array - see `Tier3Cache` above) are both this client's own state,
307
+ * so their "position" is just a plain offset into each. */
308
+ interface CompositeCursor {
309
+ tier1Cursor?: string;
310
+ tier2Offset: number;
311
+ tier3Offset: number;
312
+ /** The `Tier3Cache` entry the first page was sliced from - later pages keep slicing the same one. */
313
+ tier3Key: string;
314
+ fingerprint: string;
315
+ }
316
+
317
+ /** `undefined` for a missing, corrupted, or foreign-query cursor - every caller already treats "no
318
+ * cursor" as "start this tier from the beginning," so there's no separate error path needed here. */
319
+ function decodeCursor(raw: CompositeCursor | undefined, fingerprint: string): CompositeCursor | undefined {
320
+ return raw?.fingerprint === fingerprint ? raw : undefined;
321
+ }
322
+
323
+ /** Resolves every hit's `entityUid` to a full `Message` via `getMessage()`, reusing `cache` across
324
+ * repeated calls within the same search pass - `InboxContent`'s own search orchestration below re-merges
325
+ * and re-resolves the *entire* current hit set each time a tier resolves, so without this cache every
326
+ * stage would re-fetch messages an earlier stage already fetched. A hit whose message no longer resolves
327
+ * (deleted after being indexed, or the fetch itself failed) is cached as `null` and dropped - the same
328
+ * "a search hit can briefly outlive the message it points to" tolerance this function's inline
329
+ * predecessor already had. */
330
+ async function resolveHitsToMessages(
331
+ hits: SearchResult[],
332
+ cache: Map<string, Message | null>,
333
+ ): Promise<{ messages: Message[]; snippets: Record<string, string> }> {
334
+ const toFetch = hits.filter((hit) => !cache.has(hit.entityUid));
335
+ await Promise.all(
336
+ toFetch.map(async (hit) => {
337
+ const message = await getMessage(hit.entityUid).catch(() => null);
338
+ cache.set(hit.entityUid, message);
339
+ }),
340
+ );
341
+ const messages: Message[] = [];
342
+ const snippets: Record<string, string> = {};
343
+ for (const hit of hits) {
344
+ const message = cache.get(hit.entityUid);
345
+ if (!message) {
346
+ continue;
347
+ }
348
+ messages.push(message);
349
+ if (hit.snippet) {
350
+ snippets[message.uid] = hit.snippet;
351
+ }
352
+ }
353
+ return { messages, snippets };
354
+ }
355
+
356
+ /** How far outside the scroll container's visible area the load-more sentinel still counts as "in view". */
357
+ const LOAD_MORE_ROOT_MARGIN_PX = 200;
358
+
359
+ /** How many full pages in a row that added no new rows the list keeps loading on its own before it shows a
360
+ * "Load more" button instead. */
361
+ const MAX_EMPTY_PAGE_CONTINUATIONS = 3;
362
+
363
+ /** `true` when `more` has at least one row `shown` doesn't - i.e. appending it actually adds rows. Generic
364
+ * over the row's own identity so both the message list (`uid`) and the conversation list
365
+ * (`conversationId`) page the same way. */
366
+ function hasUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): boolean {
367
+ const seen = new Set(shown.map(idOf));
368
+ return more.some((row) => !seen.has(idOf(row)));
369
+ }
370
+
371
+ /** The load-more sentinel's actual current geometry against its scroll container, with the same margin the
372
+ * IntersectionObserver uses. */
373
+ function isWithinLoadMoreRange(sentinel: HTMLElement, root: HTMLElement): boolean {
374
+ const rect = sentinel.getBoundingClientRect();
375
+ const rootRect = root.getBoundingClientRect();
376
+ return rect.top <= rootRect.bottom + LOAD_MORE_ROOT_MARGIN_PX && rect.bottom >= rootRect.top - LOAD_MORE_ROOT_MARGIN_PX;
377
+ }
378
+
379
+ /** Appends `more` to `shown`, skipping any row already shown - a later page can repeat rows (Tier 1 and
380
+ * Tier 2/3 cursors advance independently, so the same message can come back from a different tier on a
381
+ * later page; a plain folder listing's pages shift when new mail arrives between fetches). Generic for the
382
+ * same reason `hasUnseenRows()` is. */
383
+ function appendUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): T[] {
384
+ const seen = new Set(shown.map(idOf));
385
+ const unseen: T[] = [];
386
+ for (const row of more) {
387
+ if (!seen.has(idOf(row))) {
388
+ seen.add(idOf(row));
389
+ unseen.push(row);
390
+ }
391
+ }
392
+ return unseen.length === 0 ? shown : [...shown, ...unseen];
393
+ }
394
+
395
+ const messageUid = (message: Message) => message.uid;
396
+ const conversationKey = (conversation: ConversationSummary) => conversation.conversationId;
397
+
398
+ /** Flattens and sorts a per-mailbox fetch into one merged, newest-first list - the aggregate ("All
399
+ * Inboxes" etc.) equivalent of `mergeSearchResults()` above, but simpler: an aggregated message has no
400
+ * natural relevance score to normalize, so this only ever sorts by `receivedDate`. */
401
+ function mergeInboxMessages(perMailbox: { mailbox: Mailbox; messages: Message[] }[]): Message[] {
402
+ return perMailbox
403
+ .flatMap((entry) => entry.messages)
404
+ .sort((a, b) => new Date(b.receivedDate).getTime() - new Date(a.receivedDate).getTime());
405
+ }
406
+
407
+ /**
408
+ * Fans out one `listMessages()` call per accessible mailbox that has a folder of `type`, merges the
409
+ * results newest-first. A mailbox with no matching folder, or whose fetch fails, simply contributes
410
+ * nothing - one mailbox's absence/failure must not blank out every other mailbox's messages.
411
+ *
412
+ * **Pagination scope trim (deliberate, matching this file's own documented Tier 2/3 tradeoffs)**: there is
413
+ * no composite cursor across an arbitrary number of independently-paginated mailboxes in this pass - this
414
+ * always fetches exactly each mailbox's own first page (`MESSAGE_PAGE_SIZE`) and the caller never offers a
415
+ * "load more" for the result (see `InboxContent`'s own `hasMore` handling in aggregate mode) - a real
416
+ * composite-cursor "load more" per mailbox is a natural v2 if usage shows people scrolling past the first
417
+ * page in aggregate view often.
418
+ */
419
+ async function fetchAggregateMessages(
420
+ mailboxFolders: MailboxFolders[],
421
+ type: AggregateFolderType,
422
+ filter: MessageListFilter,
423
+ ): Promise<Message[]> {
424
+ const perMailbox = await Promise.all(
425
+ mailboxFolders.map(async ({ mailbox, folders }) => {
426
+ const folder = folders.find((f) => f.type === type);
427
+ if (!folder) {
428
+ return { mailbox, messages: [] as Message[] };
429
+ }
430
+ // The filter is a server-side one per mailbox; the *sort* deliberately isn't offered here (see
431
+ // this function's own pagination scope trim) - each mailbox contributes its own newest page and
432
+ // they're merged newest-first, which a different sort key couldn't be made honest across an
433
+ // arbitrary number of independently-paged folders.
434
+ const messages = await listMessages(folder.uid, { limit: MESSAGE_PAGE_SIZE, filter }).catch(() => [] as Message[]);
435
+ return { mailbox, messages };
436
+ }),
437
+ );
438
+ return mergeInboxMessages(perMailbox);
439
+ }
440
+
441
+ export default function InboxPage(props: MailShellProps) {
442
+ return (
443
+ <MailShell {...props}>
444
+ <InboxContent userUid={props.userUid} />
445
+ </MailShell>
446
+ );
447
+ }
448
+
449
+ function InboxContent({ userUid }: { userUid?: string }) {
450
+ const { folderUid, mailboxUid, mailboxes, mailboxFolders, aggregateFolderType, onFolderCreated } = useMailShell();
451
+ const isMobile = useIsMobile();
452
+ const { requestUnlock } = useUnlockPrompt();
453
+ const [messages, setMessages] = useState<Message[]>([]);
454
+ const [conversations, setConversations] = useState<ConversationSummary[]>([]);
455
+ const [loading, setLoading] = useState(true);
456
+ const [loadingMore, setLoadingMore] = useState(false);
457
+ const [hasMore, setHasMore] = useState(false);
458
+ const [error, setError] = useState<string | null>(null);
459
+ const [selectedUid, setSelectedUid] = useState<string | null>(null);
460
+ // The thread the conversation list opened, and which of its messages was picked - the reading pane
461
+ // shows the whole conversation, positioned at that message (see `ConversationThreadPane`).
462
+ const [openThread, setOpenThread] = useState<{ conversation: ConversationSummary; uid: string } | null>(null);
463
+ // Messages the page has a newer copy of than `ConversationList` fetched (so far only the one the reading
464
+ // pane just marked read), applied over its own child rows so they don't stay bold after being read.
465
+ const [conversationPatches, setConversationPatches] = useState<Record<string, Message>>({});
466
+ // Folders this session created on demand for a bulk Delete/Report junk - see `resolveFolderOfType()`.
467
+ const lazyFoldersRef = useRef<Map<string, string>>(new Map());
468
+ const [selectMode, setSelectMode] = useState(false);
469
+ const [selectedUids, setSelectedUids] = useState<Set<string>>(new Set());
470
+ // Select mode over the *conversation* list ticks whole conversations rather than messages: the rows
471
+ // there are conversations, and a bulk action on one means "every message of it that is in this folder".
472
+ // Their messages are fetched (once, cached here) as each conversation is ticked, so the selection bar
473
+ // and every bulk action below keep working on the `Message[]` they already take.
474
+ const [selectedConversationIds, setSelectedConversationIds] = useState<Set<string>>(new Set());
475
+ const [conversationMessagesById, setConversationMessagesById] = useState<Record<string, Message[]>>({});
476
+ // A ticked conversation whose messages are still being fetched - every bulk action is held meanwhile,
477
+ // or it would act on a selection that is still arriving.
478
+ const [resolvingSelection, setResolvingSelection] = useState(0);
479
+ const [bulkBusy, setBulkBusy] = useState(false);
480
+ const [bulkError, setBulkError] = useState<string | null>(null);
481
+ // Bumped to force the list effect below to re-run - a bulk update is deliberately neither atomic nor
482
+ // all-or-nothing (see `bulkUpdateMessages()`), so a rejection means refetching rather than guessing
483
+ // which half of the selection actually landed.
484
+ const [refreshKey, setRefreshKey] = useState(0);
485
+ const [searchInput, setSearchInput] = useState("");
486
+ const [searchQuery, setSearchQuery] = useState("");
487
+ const [snippets, setSnippets] = useState<Record<string, string>>({});
488
+ // The *open mailbox's* labels, for the Filter menu's Labels submenu, select mode's Apply label, and -
489
+ // unless the selected message belongs to another mailbox - the reading pane's own Labels menu.
490
+ const [mailboxLabels, setMailboxLabels] = useState<Label[]>([]);
491
+ // The selected message's own mailbox's labels, when that is a different mailbox from the open one: in
492
+ // search and aggregate views it can be, and its labels must not be offered as a filter for this one.
493
+ // Empty (and never fetched) otherwise - see `labels` below.
494
+ const [otherMailboxLabels, setOtherMailboxLabels] = useState<Label[]>([]);
495
+ // Tier 2's own reported window coverage for the current search - undefined outside a search, or
496
+ // before Tier 2 has resolved yet for this search pass.
497
+ const [coverage, setCoverage] = useState<Coverage | undefined>(undefined);
498
+ // Keyed by message uid - see decryptEncryptedRows(). Never cleared on folder/search switches (a
499
+ // decrypted row stays decrypted while its keys stay unlocked; re-decrypting on every navigation would
500
+ // waste work for no benefit) - only cleared when the mailbox's keys are locked (see the
501
+ // `subscribeKeySession()` effect below).
502
+ const [decryptedRows, setDecryptedRows] = useState<Record<string, DecryptedRow>>({});
503
+ // Bumped after a successful on-demand unlock to re-run the search effect below - it's not a
504
+ // dependency the effect could otherwise react to (getUnlockedKeys() is a plain module-level read, not
505
+ // React state; see keySession.ts's own doc comment).
506
+ const [unlockRefresh, setUnlockRefresh] = useState(0);
507
+ // §_Progressive Results_: which of the current search's uids are still an unconfirmed Tier 1
508
+ // `metadataOnly` guess (rendered as a skeleton row - see the JSX below) - empty outside a search, and
509
+ // always empty again once every tier has reported for the current pass (each unresolved entry is by
510
+ // then either confirmed, real content, or pruned - see the search orchestration effect).
511
+ const [pendingUids, setPendingUids] = useState<Set<string>>(new Set());
512
+ // Withholds a hard result count until every tier has reported for the current search pass (§_Progressive
513
+ // Results_: "Never show a hard count until every tier has reported... A settled count is the signal
514
+ // that ordering is final"). Reset on every fresh search; irrelevant outside search mode.
515
+ const [tier1Done, setTier1Done] = useState(false);
516
+ const [tier2Done, setTier2Done] = useState(false);
517
+ const [tier3Done, setTier3Done] = useState(false);
518
+ // Toggled by the "Search all mail" action next to the results count - removes Tier 3's own default
519
+ // bound (tightened to Tier 2's coverage window otherwise - see tightenBeforeToCoverage()) for one
520
+ // re-run. Stored as the mailbox/folder/query it was requested for, not a plain flag, so it resets the
521
+ // moment any of those change - derived in the same render, so the search effect never runs a new
522
+ // query with a previous query's unbounded Tier 3 window first.
523
+ const [searchAllMailKey, setSearchAllMailKey] = useState<string | null>(null);
524
+ const searchAllMailScope = `${mailboxUid ?? ""}\n${folderUid ?? ""}\n${searchQuery}`;
525
+ const searchAllMail = searchAllMailKey === searchAllMailScope;
526
+ // The mailbox unlock/decrypt call sites below treat as "the" mailbox when there's no single selected
527
+ // one (aggregate mode) - mirrors `MailShell`'s own identical `defaultMailboxUid` fallback. An
528
+ // aggregate-view row from a *different*, not-yet-unlocked mailbox stays locked until that mailbox's
529
+ // own folder view is opened directly - an accepted limitation, not a bug (see `MailShell`'s own doc
530
+ // comment on the same tradeoff for its `LocalIndexLifecycle`/`KeyEnrollmentGate` wiring).
531
+ const activeMailboxUid = mailboxUid ?? mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
532
+ const mailboxKeys = mailboxes.find((mb) => mb.uid === activeMailboxUid)?.keys ?? [];
533
+ // The Sort/Filter menus' and "Show as conversations"' current settings, remembered per mailbox across
534
+ // reloads (`listPreferences.ts`). Read during render, not in an effect, so the very first listing
535
+ // already uses the remembered arrangement rather than fetching the default one and immediately
536
+ // refetching it - and kept per mailbox rather than as one value plus a "which mailbox is this?" check,
537
+ // so switching mailbox simply reads the other entry. What this session has changed wins over the store,
538
+ // which a storage-blocked browser refuses to keep.
539
+ const [preferencesByMailbox, setPreferencesByMailbox] = useState<Record<string, MailListPreferences>>({});
540
+ const preferences: MailListPreferences = preferencesByMailbox[activeMailboxUid] ?? getMailListPreferences(activeMailboxUid);
541
+ function updatePreferences(patch: Partial<MailListPreferences>) {
542
+ const next = { ...preferences, ...patch };
543
+ setPreferencesByMailbox((prev) => ({ ...prev, [activeMailboxUid]: next }));
544
+ setMailListPreferences(activeMailboxUid, next);
545
+ }
546
+ // Search stays real-folder-only - Tier 1/2/3 are all deeply mailbox/folder-scoped, and extending them
547
+ // to span an arbitrary number of mailboxes is out of scope for this pass (see the aggregate-fetch
548
+ // branch below, which the search effect never reaches while `folderUid` is unset).
549
+ const isSearching = !preferences.showAsConversations && searchQuery.length > 0 && !aggregateFolderType;
550
+ // Focused/Other is an Inbox-only concept (`FocusedInboxUtils.classifyMessage()` short-circuits to
551
+ // Focused for every other folder), and
552
+ // search results are ranked across folders rather than listed from one, so neither tab is offered
553
+ // there. Not offered for an aggregate view either (each mailbox classifies independently; merging
554
+ // that is out of scope).
555
+ const currentFolders = mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? [];
556
+ const currentFolderIsInbox = currentFolders.find((f) => f.uid === folderUid)?.type === "inbox";
557
+ const offerClassificationFilters = currentFolderIsInbox && !isSearching && !aggregateFolderType;
558
+ // A remembered Focused/Other filter must not silently narrow a folder that has no Focused Inbox to
559
+ // speak of - it stays remembered for when the Inbox is opened again, but doesn't apply meanwhile.
560
+ const effectiveFilter: MessageListFilter =
561
+ (preferences.filter === "focused" || preferences.filter === "other") && !offerClassificationFilters
562
+ ? "all"
563
+ : preferences.filter;
564
+ // Left out entirely rather than sent empty, so a list with no label filter asks for exactly the URL it
565
+ // always did.
566
+ const labelFilter = preferences.labelUids.length > 0 ? { labelUids: preferences.labelUids } : {};
567
+ // Every server-side list parameter the toolbar controls, in one place so the first page and each
568
+ // `loadMore()` page can't drift apart.
569
+ const listParams: MessageListParams = {
570
+ limit: MESSAGE_PAGE_SIZE,
571
+ sortBy: preferences.sortBy,
572
+ sortOrder: preferences.sortOrder,
573
+ filter: effectiveFilter,
574
+ ...labelFilter,
575
+ };
576
+ // A dependency of the list effect and of `loadMore()`, which can't take the array itself (a new one
577
+ // every render would refetch on every render).
578
+ const labelFilterKey = preferences.labelUids.join(",");
579
+ /** The sort the *server* is being asked for, as one dependency value. Empty while conversations are
580
+ * shown: `GET /mail/messages/conversations` takes no sort parameters at all, so those rows are ordered
581
+ * in the browser (`sortConversations()`) and rearranging them must not refetch the identical page -
582
+ * which would also collapse whichever conversations the reader had expanded. */
583
+ const serverSortKey = preferences.showAsConversations ? "" : `${preferences.sortBy}:${preferences.sortOrder}`;
584
+ /** The conversation list's own equivalent of `listParams` - a function because the page differs. */
585
+ function conversationParams(page: number): ConversationListParams {
586
+ return { folderUid, filter: effectiveFilter, ...labelFilter, page, limit: MESSAGE_PAGE_SIZE };
587
+ }
588
+ // How far into the folder's *current* server-side listing the rows fetched so far reach. Offset
589
+ // paging, not a cursor (`listMessages()` has none): a row removed locally (archived, scheduled send
590
+ // cancelled) also left the folder server-side, shifting every later message back by one - so each
591
+ // removal steps this back too, or the next page would silently skip a message. See `loadMore()`.
592
+ const listedOffsetRef = useRef(0);
593
+ const scrollContainerRef = useRef<HTMLDivElement | null>(null);
594
+ // State (via a callback ref), not a plain ref: the sentinel mounts and unmounts as the list loads,
595
+ // filters, and empties, and the observer effect below must re-attach to whichever node is current.
596
+ const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
597
+ const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
598
+ const loadMoreErrorRef = useRef<string | null>(null);
599
+ loadMoreErrorRef.current = loadMoreError;
600
+ const loadMoreInFlightRef = useRef(false);
601
+ // Bumped by `loadMore()` for each page that added at least one row - the only event the continuation
602
+ // effect below keeps loading after. A counter rather than watching `loadingMore` flip back to false: a
603
+ // fast response can settle before React ever renders the `true`, so that flip isn't reliably observable.
604
+ const [appendedPageCount, setAppendedPageCount] = useState(0);
605
+ // Consecutive full pages that added no new rows (every row was already shown - e.g. new mail shifted the
606
+ // folder's pages). Such a page still counts as progress for the continuation effect, up to
607
+ // `MAX_EMPTY_PAGE_CONTINUATIONS` in a row; past that, `loadMoreStalled` shows a "Load more" button
608
+ // instead, so a server that keeps repeating rows is never looped on.
609
+ const emptyPageStreakRef = useRef(0);
610
+ const [loadMoreStalled, setLoadMoreStalled] = useState(false);
611
+ const messagesRef = useRef(messages);
612
+ messagesRef.current = messages;
613
+ const conversationsRef = useRef(conversations);
614
+ conversationsRef.current = conversations;
615
+ // Reset to a fresh Map at the start of every new search pass (see the search effect below) - see
616
+ // resolveHitsToMessages()'s own doc comment on why this needs to persist *within* one pass but not
617
+ // across passes (a stale `null` for a uid that's since become resolvable elsewhere must not stick).
618
+ const resolvedMessageCacheRef = useRef<Map<string, Message | null>>(new Map());
619
+ // Session-scoped, never explicitly cleared - see Tier3Cache's own doc comment above.
620
+ const tier3CacheRef = useRef<Tier3Cache>(new Map());
621
+ // The latest composite cursor this search pass has reached - read by loadMore(), written at the end
622
+ // of both the fresh-search orchestration and loadMore() itself. Not React state: it never drives a
623
+ // render on its own, only what loadMore() does with it later.
624
+ const compositeCursorRef = useRef<CompositeCursor | undefined>(undefined);
625
+ // Guards every async load below - each search stage, the plain folder/conversation/aggregate listings,
626
+ // and `loadMore()` - against a stale, still-in-flight pass clobbering state for a newer one that started
627
+ // after it (the query, folder, or view changed) - the same `loadSeq`-style monotonic-id pattern already used elsewhere in this codebase (e.g.
628
+ // `settings/privacy/index.tsx`'s `ExportSection`), generalized here across three independently-timed
629
+ // async stages instead of one.
630
+ const searchRunIdRef = useRef(0);
631
+ // Bumped whenever `activeMailboxUid`'s keys are locked (see the `subscribeKeySession()` effect below) - a
632
+ // decrypt that started before the lock checks it before storing its now-stale plaintext rows.
633
+ const lockGenerationRef = useRef(0);
634
+ // `messages` themselves aren't a dependency here on purpose - a message uid, once decrypted, is
635
+ // never re-decrypted just because the list re-renders with the same rows (e.g. a folder-unrelated
636
+ // state update elsewhere). New rows (a fresh page load, load-more, or a completed search) each
637
+ // re-trigger this the normal way, by changing `messages` itself.
638
+ //
639
+ // Scoped to `activeMailboxUid`'s own rows only - in aggregate mode `messages` can span several
640
+ // mailboxes, but only one mailbox's keys are ever being unlocked/tracked here (see `activeMailboxUid`'s
641
+ // own doc comment above); an encrypted row from any other mailbox simply isn't a candidate for this
642
+ // auto-decrypt or the manual unlock banner below.
643
+ const undecryptedEncryptedUids = messages
644
+ .filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && !decryptedRows[m.uid] && m.mailboxUid === activeMailboxUid)
645
+ .map((m) => m.uid);
646
+
647
+ // Once unlocked, silently decrypt this page's own encrypted rows to show their real subject/preview -
648
+ // no prompt needed here, the same way searchEncryptedCandidates() already auto-includes decrypted
649
+ // matches once unlocked without asking again. Only the *first* unlock (or a fresh page of messages
650
+ // arriving) needs this; `handleUnlockList()` below covers the not-yet-unlocked case explicitly.
651
+ useEffect(() => {
652
+ if (undecryptedEncryptedUids.length === 0 || !activeMailboxUid) {
653
+ return;
654
+ }
655
+ const unlocked = getUnlockedKeys(activeMailboxUid);
656
+ if (!unlocked) {
657
+ return;
658
+ }
659
+ let cancelled = false;
660
+ const lockGeneration = lockGenerationRef.current;
661
+ void decryptEncryptedRows(
662
+ messages.filter((m) => undecryptedEncryptedUids.includes(m.uid)),
663
+ unlocked,
664
+ ).then((decrypted) => {
665
+ // A lock while this was in flight already cleared `decryptedRows` - never put them back.
666
+ if (!cancelled && lockGeneration === lockGenerationRef.current && Object.keys(decrypted).length > 0) {
667
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
668
+ }
669
+ });
670
+ return () => {
671
+ cancelled = true;
672
+ };
673
+ }, [messages, unlockRefresh]);
674
+
675
+ // Locking a mailbox's keys (idle timeout, "Destroy keys on this device now", sign-out) must take its
676
+ // decrypted content off screen too, not just out of memory: decrypted subjects/previews, search
677
+ // snippets (Tier 2/3 snippets are decrypted content), and the already-decrypted Tier 3 candidates. A
678
+ // live search re-runs, so Tier 2/3 contribute nothing again until the user unlocks. Read through a ref
679
+ // so the subscription itself doesn't churn on every render.
680
+ const keyLockStateRef = useRef({ activeMailboxUid, isSearching });
681
+ keyLockStateRef.current = { activeMailboxUid, isSearching };
682
+ useEffect(
683
+ () =>
684
+ subscribeKeySession(({ mailboxUid: changedMailboxUid, state }) => {
685
+ const current = keyLockStateRef.current;
686
+ if (state !== "locked" || changedMailboxUid !== current.activeMailboxUid) {
687
+ return;
688
+ }
689
+ lockGenerationRef.current += 1;
690
+ setDecryptedRows({});
691
+ setSnippets({});
692
+ tier3CacheRef.current.clear();
693
+ if (current.isSearching) {
694
+ setUnlockRefresh((n) => n + 1);
695
+ }
696
+ }),
697
+ [],
698
+ );
699
+
700
+ async function handleUnlockList() {
701
+ try {
702
+ const unlocked = await requestUnlock(activeMailboxUid, mailboxKeys);
703
+ const lockGeneration = lockGenerationRef.current;
704
+ const decrypted = await decryptEncryptedRows(
705
+ messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && m.mailboxUid === activeMailboxUid),
706
+ unlocked,
707
+ );
708
+ if (lockGeneration === lockGenerationRef.current) {
709
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
710
+ }
711
+ } catch {
712
+ // User dismissed the unlock dialog - rows stay exactly as they were.
713
+ }
714
+ }
715
+
716
+ async function handleUnlockSearch() {
717
+ try {
718
+ await requestUnlock(activeMailboxUid, mailboxKeys);
719
+ setUnlockRefresh((n) => n + 1);
720
+ } catch {
721
+ // User dismissed the unlock dialog - the search results stay exactly as they were.
722
+ }
723
+ }
724
+
725
+ // Labels are mailbox-wide, not folder-scoped - fetched once per mailbox rather than per message, and
726
+ // handed to the detail pane below. A failure here just means the Labels control stays hidden (an empty
727
+ // `labels` array) rather than blocking the rest of the inbox. Keyed on the *selected message's own*
728
+ // mailbox: aggregate views and search results can show messages from a mailbox other than
729
+ // `activeMailboxUid`, and offering that mailbox's labels would let a label from the wrong mailbox be
730
+ // applied. The conversation view stays scoped to `activeMailboxUid`, the mailbox its threads come from.
731
+ const selectedMessageMailboxUid = messages.find((m) => m.uid === selectedUid)?.mailboxUid;
732
+ const labelsMailboxUid = preferences.showAsConversations ? activeMailboxUid : (selectedMessageMailboxUid ?? activeMailboxUid);
733
+ // Almost always the open mailbox's own labels, already fetched below - so `labels` reuses that list
734
+ // rather than asking for the identical one a second time (which is what this page did on every single
735
+ // view). Only a selected message from *another* mailbox - a search hit or an aggregate-view row - needs
736
+ // its own fetch, and only then is this state used at all.
737
+ const otherMailbox = labelsMailboxUid !== activeMailboxUid;
738
+ const labels = otherMailbox ? otherMailboxLabels : mailboxLabels;
739
+ // `labelsMailboxUid` is always set: `MailShell` only renders this component once at least one mailbox
740
+ // exists, so `activeMailboxUid` (its fallback) always resolves.
741
+ useEffect(() => {
742
+ if (!otherMailbox) {
743
+ setOtherMailboxLabels([]);
744
+ return;
745
+ }
746
+ let cancelled = false;
747
+ setOtherMailboxLabels([]);
748
+ listLabels(labelsMailboxUid, { limit: 200 })
749
+ .then((result) => {
750
+ if (!cancelled) {
751
+ setOtherMailboxLabels(result);
752
+ }
753
+ })
754
+ .catch(() => undefined);
755
+ return () => {
756
+ cancelled = true;
757
+ };
758
+ }, [labelsMailboxUid, otherMailbox]);
759
+
760
+ useEffect(() => {
761
+ let cancelled = false;
762
+ setMailboxLabels([]);
763
+ listLabels(activeMailboxUid, { limit: 200 })
764
+ .then((result) => {
765
+ if (!cancelled) {
766
+ setMailboxLabels(result);
767
+ }
768
+ })
769
+ .catch(() => undefined);
770
+ return () => {
771
+ cancelled = true;
772
+ };
773
+ }, [activeMailboxUid]);
774
+
775
+ // Debounce the raw input into the query actually searched, so every keystroke doesn't fire a request.
776
+ useEffect(() => {
777
+ const handle = setTimeout(() => setSearchQuery(searchInput.trim()), SEARCH_DEBOUNCE_MS);
778
+ return () => clearTimeout(handle);
779
+ }, [searchInput]);
780
+
781
+ // Loads whichever list the current folder, arrangement and search state call for, and resets every
782
+ // piece of per-listing state (selection, paging, select mode) that a previous listing left behind.
783
+ useEffect(() => {
784
+ setSelectedUid(null);
785
+ setOpenThread(null);
786
+ setConversationPatches({});
787
+ setSelectedUids(new Set());
788
+ setSelectedConversationIds(new Set());
789
+ setConversationMessagesById({});
790
+ listedOffsetRef.current = 0;
791
+ compositeCursorRef.current = undefined;
792
+ setHasMore(false);
793
+ setLoadMoreError(null);
794
+ setLoadMoreStalled(false);
795
+ emptyPageStreakRef.current = 0;
796
+ // Every run - search or not - supersedes whatever an earlier run (or a `loadMore()` it started)
797
+ // still has in flight; each async callback below checks this before touching state.
798
+ searchRunIdRef.current += 1;
799
+ const myRunId = searchRunIdRef.current;
800
+ const isCurrentRun = () => searchRunIdRef.current === myRunId;
801
+ // Also invalidates on unmount, so nothing lands after the component is gone. Unconditional: this
802
+ // cleanup only ever runs for the latest run of this effect (React runs it before the next run
803
+ // bumps the id, or on unmount), so the id is always still `myRunId` here.
804
+ const invalidate = () => {
805
+ searchRunIdRef.current += 1;
806
+ };
807
+
808
+ if (!folderUid && !aggregateFolderType) {
809
+ // The shell hasn't resolved this mailbox's folders yet (the render below says so). Listing
810
+ // anything now means a request whose answer is thrown away the moment the Inbox arrives - and
811
+ // for conversations a mailbox-wide grouping pass, the most expensive listing there is.
812
+ setMessages([]);
813
+ setConversations([]);
814
+ setLoading(false);
815
+ return;
816
+ }
817
+ if (aggregateFolderType && mailboxFolders.length === 0) {
818
+ // The same, for a merged view: it has no folder of its own, but it is built from every
819
+ // mailbox's folders, and this effect re-runs the moment they arrive. Listing twice is what
820
+ // that cost before.
821
+ setMessages([]);
822
+ setConversations([]);
823
+ setLoading(true);
824
+ return;
825
+ }
826
+
827
+ if (preferences.showAsConversations) {
828
+ // Conversations stay single-mailbox (not aggregated across mailboxes in this pass) - in
829
+ // aggregate mode this falls back to `activeMailboxUid`, the same mailbox unlock/labels use
830
+ // (always set - `MailShell` only renders this component once at least one mailbox exists).
831
+ // They're scoped to the selected folder (`folderUid`, absent only in aggregate mode), so the
832
+ // conversation list matches the folder the sidebar has selected rather than the whole mailbox.
833
+ setLoading(true);
834
+ setError(null);
835
+ listConversations(activeMailboxUid, conversationParams(0))
836
+ .then((result) => {
837
+ if (isCurrentRun()) {
838
+ setConversations(result);
839
+ listedOffsetRef.current = result.length;
840
+ setHasMore(result.length === MESSAGE_PAGE_SIZE);
841
+ }
842
+ })
843
+ .catch((err) => {
844
+ if (isCurrentRun()) {
845
+ setError(err instanceof ApiRequestError ? err.message : "Could not load conversations.");
846
+ }
847
+ })
848
+ .finally(() => {
849
+ if (isCurrentRun()) {
850
+ setLoading(false);
851
+ }
852
+ });
853
+ return invalidate;
854
+ }
855
+
856
+ if (aggregateFolderType) {
857
+ setLoading(true);
858
+ setError(null);
859
+ // hasMore stays false (set above) - see fetchAggregateMessages()'s own pagination scope trim.
860
+ void fetchAggregateMessages(mailboxFolders, aggregateFolderType, effectiveFilter)
861
+ .then((results) => {
862
+ if (isCurrentRun()) {
863
+ setMessages(results);
864
+ }
865
+ })
866
+ .finally(() => {
867
+ if (isCurrentRun()) {
868
+ setLoading(false);
869
+ }
870
+ });
871
+ return invalidate;
872
+ }
873
+
874
+ setLoading(true);
875
+ setError(null);
876
+
877
+ if (isSearching) {
878
+ setCoverage(undefined);
879
+ setPendingUids(new Set());
880
+ setTier1Done(false);
881
+ setTier2Done(false);
882
+ setTier3Done(false);
883
+ resolvedMessageCacheRef.current = new Map();
884
+ const parsed = parseSearchQuery(searchQuery);
885
+ const unlocked = getUnlockedKeys(mailboxUid!);
886
+ const fingerprint = queryFingerprint(parsed);
887
+
888
+ // Recomputes and re-renders the merged list from whatever tiers have reported so far -
889
+ // called once after Tier 1+2 (interim: unconfirmed Tier 1 metadataOnly hits render as
890
+ // skeletons) and again after Tier 3 (final: anything still unconfirmed is pruned instead -
891
+ // §_Progressive Results_' "Skeletons resolve or disappear"). Bails out via `myRunId` if a
892
+ // newer search pass has since started.
893
+ async function reveal(tier1Hits: SearchResult[], tier2Hits: SearchResult[], tier3Hits: SearchResult[], final: boolean) {
894
+ const capped = capSkeletons(tier1Hits);
895
+ const confirmed = new Set([...tier2Hits, ...tier3Hits].map((r) => r.entityUid));
896
+ const effectiveTier1 = final ? capped.filter((hit) => !hit.metadataOnly || confirmed.has(hit.entityUid)) : capped;
897
+ const merged = mergeSearchResults(effectiveTier1, tier2Hits, tier3Hits);
898
+ const { messages: resolved, snippets: resolvedSnippets } = await resolveHitsToMessages(
899
+ merged,
900
+ resolvedMessageCacheRef.current,
901
+ );
902
+ if (searchRunIdRef.current !== myRunId) {
903
+ return;
904
+ }
905
+ setMessages(resolved);
906
+ setSnippets(resolvedSnippets);
907
+ if (final) {
908
+ setPendingUids(new Set());
909
+ } else {
910
+ const pending = new Set<string>();
911
+ for (const hit of capped) {
912
+ if (hit.metadataOnly && !confirmed.has(hit.entityUid)) {
913
+ pending.add(hit.entityUid);
914
+ }
915
+ }
916
+ setPendingUids(pending);
917
+ }
918
+ }
919
+
920
+ void (async () => {
921
+ try {
922
+ const [tier1Page, tier2Page] = await Promise.all([
923
+ searchMailbox(parsed.text, tier1SearchParams(parsed, undefined, mailboxUid!)),
924
+ searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, 0),
925
+ ]);
926
+ if (searchRunIdRef.current !== myRunId) {
927
+ return;
928
+ }
929
+ setTier1Done(true);
930
+ setTier2Done(true);
931
+ setCoverage(tier2Page.coverage);
932
+ setLoading(false);
933
+ await reveal(tier1Page.results, tier2Page.results, [], false);
934
+
935
+ const windows = tier3Windows(parsed, tier2Page.coverage, searchAllMail);
936
+ const cacheKey = tier3CacheKey(mailboxUid!, windows, !!unlocked);
937
+ let tier3Full = tier3CacheRef.current.get(cacheKey);
938
+ if (!tier3Full) {
939
+ tier3Full = await searchTier3Windows(windows, unlocked, mailboxUid!);
940
+ if (searchRunIdRef.current !== myRunId) {
941
+ return;
942
+ }
943
+ tier3CacheRef.current.set(cacheKey, tier3Full);
944
+ }
945
+ const tier3Page = tier3Full.slice(0, MESSAGE_PAGE_SIZE);
946
+ setTier3Done(true);
947
+ compositeCursorRef.current = {
948
+ tier1Cursor: tier1Page.nextCursor,
949
+ tier2Offset: tier2Page.results.length,
950
+ tier3Offset: tier3Page.length,
951
+ tier3Key: cacheKey,
952
+ fingerprint,
953
+ };
954
+ setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || tier3Page.length < tier3Full.length);
955
+ await reveal(tier1Page.results, tier2Page.results, tier3Page, true);
956
+ } catch (err) {
957
+ if (searchRunIdRef.current === myRunId) {
958
+ setError(err instanceof ApiRequestError ? err.message : "Search failed.");
959
+ setLoading(false);
960
+ }
961
+ }
962
+ })();
963
+ return invalidate;
964
+ }
965
+
966
+ // Set: the guard at the top of this effect returned for a view with neither a folder nor an
967
+ // aggregate type, and the aggregate branch above returned for the one with an aggregate type.
968
+ listMessages(folderUid!, listParams)
969
+ .then((results) => {
970
+ if (isCurrentRun()) {
971
+ setMessages(results);
972
+ listedOffsetRef.current = results.length;
973
+ setHasMore(results.length === MESSAGE_PAGE_SIZE);
974
+ }
975
+ })
976
+ .catch((err) => {
977
+ if (isCurrentRun()) {
978
+ setError(err instanceof ApiRequestError ? err.message : "Could not load messages.");
979
+ }
980
+ })
981
+ .finally(() => {
982
+ if (isCurrentRun()) {
983
+ setLoading(false);
984
+ }
985
+ });
986
+ return invalidate;
987
+ // `unlockRefresh`/`searchAllMail` are dependencies solely so `handleUnlockSearch()`/"Search all
988
+ // mail" can force this effect to re-run the search above - Tier 3 (encrypted) results silently
989
+ // contribute nothing without unlocked keys, so this is what actually makes them appear once the
990
+ // user unlocks, and what makes "Search all mail" actually remove Tier 3's coverage bound. Neither
991
+ // has any effect on the non-search branch below; re-running it with identical inputs just
992
+ // re-fetches the same page.
993
+ // `refreshKey` is a dependency for the same reason: a failed bulk action bumps it to refetch,
994
+ // since a bulk update applies until its first rejection rather than all-or-nothing.
995
+ }, [
996
+ preferences.showAsConversations,
997
+ serverSortKey,
998
+ effectiveFilter,
999
+ labelFilterKey,
1000
+ refreshKey,
1001
+ folderUid,
1002
+ mailboxUid,
1003
+ isSearching,
1004
+ searchQuery,
1005
+ unlockRefresh,
1006
+ searchAllMail,
1007
+ aggregateFolderType,
1008
+ mailboxFolders,
1009
+ activeMailboxUid,
1010
+ ]);
1011
+
1012
+ function handleSearchAllMail() {
1013
+ setSearchAllMailKey(searchAllMailScope);
1014
+ }
1015
+
1016
+ const loadMore = useCallback(async () => {
1017
+ const parsed = parseSearchQuery(searchQuery);
1018
+ const fingerprint = queryFingerprint(parsed);
1019
+ // While searching, a load-more continues from this query's own cursor - absent until its first page
1020
+ // has fully finished (the ref may still hold an earlier query's), in which case there's nowhere to
1021
+ // continue from yet.
1022
+ const searchCursor = decodeCursor(compositeCursorRef.current, fingerprint);
1023
+ if (
1024
+ loadMoreInFlightRef.current ||
1025
+ !hasMore ||
1026
+ loading ||
1027
+ (!preferences.showAsConversations && !folderUid) ||
1028
+ (isSearching && !searchCursor)
1029
+ ) {
1030
+ return;
1031
+ }
1032
+ // A ref, not `loadingMore` state: the observer and the continuation effect below can both call in the
1033
+ // same tick, each closing over a render where `loadingMore` was still false.
1034
+ loadMoreInFlightRef.current = true;
1035
+ setLoadMoreError(null);
1036
+ setLoadMoreStalled(false);
1037
+ setLoadingMore(true);
1038
+ /** Records whether a landed page added rows, and whether the continuation effect should keep going. */
1039
+ const notePageLanded = (addedRows: boolean, moreRemain: boolean) => {
1040
+ if (addedRows) {
1041
+ emptyPageStreakRef.current = 0;
1042
+ setAppendedPageCount((n) => n + 1);
1043
+ } else if (moreRemain) {
1044
+ emptyPageStreakRef.current += 1;
1045
+ if (emptyPageStreakRef.current <= MAX_EMPTY_PAGE_CONTINUATIONS) {
1046
+ setAppendedPageCount((n) => n + 1);
1047
+ } else {
1048
+ emptyPageStreakRef.current = 0;
1049
+ setLoadMoreStalled(true);
1050
+ }
1051
+ }
1052
+ };
1053
+ // A query/folder/view change while this page is in flight bumps the run id (see the effect above) -
1054
+ // its rows then belong to a list that's no longer on screen and must not be appended to the new one.
1055
+ const myRunId = searchRunIdRef.current;
1056
+ const isCurrentRun = () => searchRunIdRef.current === myRunId;
1057
+ try {
1058
+ if (preferences.showAsConversations) {
1059
+ const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1060
+ const more = await listConversations(activeMailboxUid, conversationParams(page));
1061
+ if (!isCurrentRun()) {
1062
+ return;
1063
+ }
1064
+ const addedRows = hasUnseenRows(conversationsRef.current, more, conversationKey);
1065
+ setConversations((prev) => appendUnseenRows(prev, more, conversationKey));
1066
+ setHasMore(more.length === MESSAGE_PAGE_SIZE);
1067
+ listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1068
+ notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1069
+ } else if (isSearching) {
1070
+ const unlocked = getUnlockedKeys(mailboxUid!);
1071
+ const cursor = searchCursor!;
1072
+
1073
+ const [tier1Page, tier2Page] = await Promise.all([
1074
+ searchMailbox(parsed.text, tier1SearchParams(parsed, cursor.tier1Cursor, mailboxUid!)),
1075
+ searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, cursor.tier2Offset),
1076
+ ]);
1077
+ // The first page cached this pass under `tier3Key` before it created the cursor.
1078
+ const tier3Full = tier3CacheRef.current.get(cursor.tier3Key)!;
1079
+ const tier3Offset = cursor.tier3Offset;
1080
+ const tier3Page = tier3Full.slice(tier3Offset, tier3Offset + MESSAGE_PAGE_SIZE);
1081
+
1082
+ // Unlike the fresh-search pass above, a load-more page is resolved and appended in one
1083
+ // shot rather than progressively revealed - rows already on screen shouldn't reorder or
1084
+ // grow skeletons out from under a reader who has since scrolled past them. Any Tier 1
1085
+ // metadataOnly hit this page that neither Tier 2 nor Tier 3 (both already awaited above)
1086
+ // confirms simply keeps showing its existing placeholder text rather than a live skeleton
1087
+ // - a deliberate, documented scope trim of progressive reveal to the first page only.
1088
+ const merged = mergeSearchResults(capSkeletons(tier1Page.results), tier2Page.results, tier3Page);
1089
+ const { messages: more, snippets: moreSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
1090
+ if (!isCurrentRun()) {
1091
+ return;
1092
+ }
1093
+ const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1094
+ setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1095
+ setSnippets((prev) => ({ ...prev, ...moreSnippets }));
1096
+
1097
+ const nextTier3Offset = tier3Offset + tier3Page.length;
1098
+ compositeCursorRef.current = {
1099
+ tier1Cursor: tier1Page.nextCursor,
1100
+ tier2Offset: cursor.tier2Offset + tier2Page.results.length,
1101
+ tier3Offset: nextTier3Offset,
1102
+ tier3Key: cursor.tier3Key,
1103
+ fingerprint,
1104
+ };
1105
+ const moreRemain = !!tier1Page.nextCursor || tier2Page.hasMore || nextTier3Offset < tier3Full.length;
1106
+ setHasMore(moreRemain);
1107
+ notePageLanded(addedRows, moreRemain);
1108
+ } else {
1109
+ // The page containing the first message not fetched yet. After a local removal that offset is
1110
+ // no longer a page boundary, so this page overlaps rows already shown - `appendUnseenRows()`
1111
+ // drops those - rather than skipping the message that shifted back across the boundary.
1112
+ const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1113
+ const more = await listMessages(folderUid!, { ...listParams, page });
1114
+ if (!isCurrentRun()) {
1115
+ return;
1116
+ }
1117
+ const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1118
+ setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1119
+ setHasMore(more.length === MESSAGE_PAGE_SIZE);
1120
+ listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1121
+ notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1122
+ }
1123
+ } catch (err) {
1124
+ // Shown next to the sentinel with a Retry button - never auto-retried (see the continuation
1125
+ // effect below), so a failing server isn't hammered while the sentinel stays in view.
1126
+ if (isCurrentRun()) {
1127
+ setLoadMoreError(err instanceof ApiRequestError ? err.message : "Could not load more messages.");
1128
+ }
1129
+ } finally {
1130
+ loadMoreInFlightRef.current = false;
1131
+ setLoadingMore(false);
1132
+ }
1133
+ }, [
1134
+ hasMore,
1135
+ loading,
1136
+ preferences.showAsConversations,
1137
+ serverSortKey,
1138
+ effectiveFilter,
1139
+ labelFilterKey,
1140
+ folderUid,
1141
+ isSearching,
1142
+ searchQuery,
1143
+ mailboxUid,
1144
+ activeMailboxUid,
1145
+ ]);
1146
+
1147
+ // Always calls the latest `loadMore` closure so the effect below doesn't need `loadMore` itself in its
1148
+ // dependency array (it changes on every keystroke/page load, which would otherwise mean nothing here).
1149
+ const loadMoreRef = useRef(loadMore);
1150
+ loadMoreRef.current = loadMore;
1151
+
1152
+ // Keyed on the sentinel node itself (see `sentinel`'s own comment): it unmounts whenever the list shows
1153
+ // "Loading..." and remounts afterwards, so an observer attached once to an earlier node would watch a
1154
+ // detached element forever. Only ever rendered in "By date" mode, so no view-mode check is needed.
1155
+ useEffect(() => {
1156
+ if (!sentinel) {
1157
+ return;
1158
+ }
1159
+ const observer = new IntersectionObserver(
1160
+ (entries) => {
1161
+ if (entries.some((entry) => entry.isIntersecting) && !loadMoreErrorRef.current) {
1162
+ void loadMoreRef.current();
1163
+ }
1164
+ },
1165
+ { root: scrollContainerRef.current, rootMargin: `${LOAD_MORE_ROOT_MARGIN_PX}px` },
1166
+ );
1167
+ observer.observe(sentinel);
1168
+ return () => observer.disconnect();
1169
+ }, [sentinel]);
1170
+
1171
+ // An observer only reports *changes* - a sentinel still in view after a page lands (the new rows didn't
1172
+ // push it out of view, e.g. the Focused/Other filter hid every one of them) never reports again, so
1173
+ // keep loading while it's still in view. Only after a page that appended rows, or a full page of rows
1174
+ // already shown (bounded - see `emptyPageStreakRef`), never after a failure, and only when the sentinel's
1175
+ // real geometry says it's still in view (the observer's last report may predate the rows that just landed).
1176
+ useEffect(() => {
1177
+ if (appendedPageCount === 0) {
1178
+ return;
1179
+ }
1180
+ // The scroll container is always mounted whenever a sentinel is (the sentinel lives inside it).
1181
+ if (sentinel && isWithinLoadMoreRange(sentinel, scrollContainerRef.current!)) {
1182
+ void loadMoreRef.current();
1183
+ }
1184
+ }, [appendedPageCount]);
1185
+
1186
+ /**
1187
+ * Replaces one listed row - and, in the conversation list, the opened message and the child row
1188
+ * standing for it - with a newer copy the reading pane just produced.
1189
+ *
1190
+ * A conversation's *parent* row has no copy to replace: it is a summary of the whole thread, and its
1191
+ * "2 unread" chip and bold styling come from a count the server worked out when the list was fetched.
1192
+ * So when the reading pane reports a message it has just read (`previous` unread, `updated` read), that
1193
+ * count is decremented here - otherwise a conversation kept claiming unread mail the reader had just
1194
+ * read, until the whole list was reloaded.
1195
+ */
1196
+ function patchListedMessage(updated: Message, previous?: Message) {
1197
+ setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)));
1198
+ // `ConversationList` fetched its own copy of this message when the thread was expanded; hand it the
1199
+ // newer one so the child row doesn't keep showing a stale read/flag state.
1200
+ setConversationPatches((prev) => ({ ...prev, [updated.uid]: updated }));
1201
+ if (previous && !previous.flags.read && updated.flags.read) {
1202
+ setConversations((prev) =>
1203
+ prev.map((conversation) =>
1204
+ conversation.messageUids.includes(updated.uid)
1205
+ ? { ...conversation, unreadCount: Math.max(0, conversation.unreadCount - 1) }
1206
+ : conversation,
1207
+ ),
1208
+ );
1209
+ }
1210
+ }
1211
+
1212
+ function removeListedMessages(uids: Set<string>) {
1213
+ setMessages((prev) => prev.filter((m) => !uids.has(m.uid)));
1214
+ listedOffsetRef.current = Math.max(0, listedOffsetRef.current - uids.size);
1215
+ setSelectedUid((prev) => (prev && uids.has(prev) ? null : prev));
1216
+ }
1217
+
1218
+ function removeListedMessage(uid: string) {
1219
+ removeListedMessages(new Set([uid]));
1220
+ }
1221
+
1222
+ // The conversation list opens a whole thread in `ConversationThreadPane`, which loads and marks read
1223
+ // its own messages; only the flat list feeds the single-message pane below.
1224
+ const selected = preferences.showAsConversations ? null : (messages.find((m) => m.uid === selectedUid) ?? null);
1225
+ const attachments = useMessageAttachments(selected);
1226
+ useMarkMessageRead(selected, patchListedMessage);
1227
+ // Search results can span every folder in the mailbox, not just the one selected in the sidebar - a
1228
+ // selected message's own folderUid is the only reliable source for its actual folder type once
1229
+ // searching (outside search, every message in `messages` already comes from `folderUid` itself, so
1230
+ // this falls back to the sidebar selection unchanged). Aggregate views span every *mailbox* too, so
1231
+ // the folder list consulted is the selected message's own mailbox's, not the shell's ambient one. A
1232
+ // conversation spans folders for the same reason (an Inbox message and the Sent Items copy of its reply).
1233
+ const spansFolders = isSearching || !!aggregateFolderType || preferences.showAsConversations;
1234
+ const selectedFolderUid = spansFolders ? (selected?.folderUid ?? folderUid) : folderUid;
1235
+ const selectedMailboxUid = spansFolders ? (selected?.mailboxUid ?? activeMailboxUid) : mailboxUid;
1236
+ const folders = mailboxFolders.find((mf) => mf.mailbox.uid === selectedMailboxUid)?.folders ?? [];
1237
+ const isSentItems = folders.find((f) => f.uid === selectedFolderUid)?.type === "sent_items";
1238
+ const isOutbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "outbox";
1239
+ const draftsFolderUid = folders.find((f) => f.type === "drafts")?.uid;
1240
+
1241
+ /** What a row actually shows as its subject - the decrypted one where this device recovered it, a
1242
+ * readable stand-in for an encrypted one it hasn't, and a placeholder for a message with no subject. */
1243
+ function rowSubject(message: Message): string {
1244
+ return (
1245
+ decryptedRows[message.uid]?.subject ||
1246
+ (message.subject === ENCRYPTED_SUBJECT_PLACEHOLDER ? "Encrypted message" : message.subject) ||
1247
+ "(no subject)"
1248
+ );
1249
+ }
1250
+
1251
+ /** The conversation list's selection as plain messages: every message of every ticked conversation
1252
+ * that is in the folder being listed. A conversation spans folders (an Inbox message and the Sent
1253
+ * Items copy of its reply), and the list only ever showed this folder's half of it, so a bulk action
1254
+ * from here must not reach into the other folders' copies either. */
1255
+ const selectedConversationMessages = [...selectedConversationIds].flatMap((id) =>
1256
+ (conversationMessagesById[id] ?? []).filter((m) => !folderUid || m.folderUid === folderUid),
1257
+ );
1258
+ const selectedMessages = preferences.showAsConversations
1259
+ ? selectedConversationMessages
1260
+ : messages.filter((m) => selectedUids.has(m.uid));
1261
+ /** How many rows the list is actually showing - conversations or messages, whichever it lists. What the
1262
+ * Select toggle is enabled by: there is nothing to select in a list with no rows. */
1263
+ const listedRowCount = preferences.showAsConversations ? conversations.length : messages.length;
1264
+ /** The conversation rows in the order the reader arranged them. The endpoint takes no sort parameters
1265
+ * of its own (it pages by latest activity), so the arrangement is applied here, to the rows fetched so
1266
+ * far - which the Sort menu says on screen. `conversations` itself stays in the order the pages
1267
+ * arrived, so paging keeps appending to the same accumulated set. */
1268
+ const listedConversations = sortConversations(conversations, preferences.sortBy, preferences.sortOrder);
1269
+
1270
+ function leaveSelectMode() {
1271
+ setSelectMode(false);
1272
+ setSelectedUids(new Set());
1273
+ setSelectedConversationIds(new Set());
1274
+ setBulkError(null);
1275
+ }
1276
+
1277
+ function toggleSelected(uid: string) {
1278
+ setSelectedUids((prev) => {
1279
+ const next = new Set(prev);
1280
+ if (next.has(uid)) {
1281
+ next.delete(uid);
1282
+ } else {
1283
+ next.add(uid);
1284
+ }
1285
+ return next;
1286
+ });
1287
+ }
1288
+
1289
+ /** Loads (once) the messages behind each of `ids`, so a ticked conversation resolves to the messages
1290
+ * every bulk action below acts on. If any of them fails to load, none of that batch stays ticked and
1291
+ * the bar says why - better than acting on the part of a selection that happened to arrive. */
1292
+ async function resolveConversations(ids: string[]) {
1293
+ const missing = ids.filter((id) => !conversationMessagesById[id]);
1294
+ if (missing.length === 0) {
1295
+ return;
1296
+ }
1297
+ setResolvingSelection((n) => n + 1);
1298
+ try {
1299
+ const loaded = await Promise.all(
1300
+ missing.map(async (id) => [id, await listConversationMessages(activeMailboxUid, id)] as const),
1301
+ );
1302
+ setConversationMessagesById((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));
1303
+ } catch (err) {
1304
+ setBulkError(
1305
+ err instanceof ApiRequestError ? err.message : "Could not load the messages in one of those conversations.",
1306
+ );
1307
+ setSelectedConversationIds((prev) => {
1308
+ const next = new Set(prev);
1309
+ for (const id of missing) {
1310
+ next.delete(id);
1311
+ }
1312
+ return next;
1313
+ });
1314
+ } finally {
1315
+ setResolvingSelection((n) => n - 1);
1316
+ }
1317
+ }
1318
+
1319
+ function toggleConversationSelected(conversation: ConversationSummary) {
1320
+ const id = conversation.conversationId;
1321
+ const ticking = !selectedConversationIds.has(id);
1322
+ setSelectedConversationIds((prev) => {
1323
+ const next = new Set(prev);
1324
+ if (ticking) {
1325
+ next.add(id);
1326
+ } else {
1327
+ next.delete(id);
1328
+ }
1329
+ return next;
1330
+ });
1331
+ if (ticking) {
1332
+ void resolveConversations([id]);
1333
+ }
1334
+ }
1335
+
1336
+ function selectAllConversations() {
1337
+ const ids = conversations.map(conversationKey);
1338
+ setSelectedConversationIds(new Set(ids));
1339
+ void resolveConversations(ids);
1340
+ }
1341
+
1342
+ /**
1343
+ * Runs one bulk action over the current selection, then either patches the affected rows in place or
1344
+ * drops them (a move takes them out of the folder being listed).
1345
+ *
1346
+ * A bulk update is applied element by element server-side and stops at its first rejection, so a
1347
+ * failure leaves an unknown prefix of the selection already changed (see `bulkUpdateMessages()`) -
1348
+ * which is why a failure reloads the list rather than trying to reconcile it, and says so.
1349
+ */
1350
+ async function runBulkAction(action: (chosen: Message[]) => Promise<Message[]>, removesRows: boolean) {
1351
+ const chosen = selectedMessages;
1352
+ setBulkBusy(true);
1353
+ setBulkError(null);
1354
+ try {
1355
+ const updated = await action(chosen);
1356
+ if (preferences.showAsConversations) {
1357
+ // A conversation row is a summary of its messages - its count, unread count, participants
1358
+ // and preview all move when a bulk action changes or empties part of it - so the list is
1359
+ // reloaded rather than patched row by row.
1360
+ setSelectedConversationIds(new Set());
1361
+ setConversationMessagesById({});
1362
+ setRefreshKey((n) => n + 1);
1363
+ } else if (removesRows) {
1364
+ removeListedMessages(new Set(chosen.map((m) => m.uid)));
1365
+ } else {
1366
+ const byUid = new Map(updated.map((m) => [m.uid, m]));
1367
+ setMessages((prev) => prev.map((m) => byUid.get(m.uid) ?? m));
1368
+ }
1369
+ setSelectedUids(new Set());
1370
+ } catch (err) {
1371
+ setBulkError(
1372
+ `${err instanceof ApiRequestError ? err.message : "Those messages couldn't all be updated."} Some of them may already have changed, so the list has been reloaded.`,
1373
+ );
1374
+ setSelectedUids(new Set());
1375
+ setSelectedConversationIds(new Set());
1376
+ setConversationMessagesById({});
1377
+ setRefreshKey((n) => n + 1);
1378
+ } finally {
1379
+ setBulkBusy(false);
1380
+ }
1381
+ }
1382
+
1383
+ /** Archive has no folder to move into until the mailbox has one: the server creates it lazily on the
1384
+ * first single-message archive, so that call both creates the folder and archives the first message,
1385
+ * and the rest of the selection is then moved into the folder it reports. */
1386
+ async function bulkArchive(chosen: Message[]): Promise<Message[]> {
1387
+ const archiveFolderUid = currentFolders.find((f) => f.type === "archive")?.uid;
1388
+ if (archiveFolderUid) {
1389
+ return moveMessages(chosen, archiveFolderUid);
1390
+ }
1391
+ const first = await archiveMessage(chosen[0].uid);
1392
+ const rest = chosen.slice(1);
1393
+ return rest.length === 0 ? [first] : [first, ...(await moveMessages(rest, first.folderUid))];
1394
+ }
1395
+
1396
+ /**
1397
+ * This mailbox's folder of `type`, created on demand. A mailbox is provisioned with only the folders it
1398
+ * has needed so far, so Deleted Items and Junk may genuinely not exist the first time a selection is
1399
+ * deleted or reported - and unlike Archive, neither has a server-side lazy-create route to go through.
1400
+ *
1401
+ * A folder created here isn't in `mailboxFolders` (the shell fetched that once), so it's remembered per
1402
+ * mailbox and type until the page reloads; otherwise a second Delete would create a second folder.
1403
+ */
1404
+ async function resolveFolderOfType(type: Folder["type"], name: string): Promise<string> {
1405
+ const key = `${activeMailboxUid}:${type}`;
1406
+ const known = currentFolders.find((f) => f.type === type)?.uid ?? lazyFoldersRef.current.get(key);
1407
+ if (known) {
1408
+ return known;
1409
+ }
1410
+ const created = await createFolder({ mailboxUid: activeMailboxUid, name, type });
1411
+ lazyFoldersRef.current.set(key, created.uid);
1412
+ return created.uid;
1413
+ }
1414
+
1415
+ /**
1416
+ * Sets every selected message's labels in one bulk update: each ends up with `labelUids`, plus the
1417
+ * ones left partially applied (`keepPartial`) that it already had, plus any label this mailbox no
1418
+ * longer defines - a label the menu couldn't show isn't one the reader chose to remove.
1419
+ *
1420
+ * `bulkUpdateMessages()` rather than `setMessagesLabels()`, which is its one-list-for-everyone special
1421
+ * case: with a partially-applied row each message keeps a *different* list.
1422
+ */
1423
+ function applyLabelsToSelection(labelUids: string[], keepPartial: string[]) {
1424
+ void runBulkAction(
1425
+ (chosen) =>
1426
+ bulkUpdateMessages(
1427
+ chosen.map((message) => {
1428
+ const kept = (message.labelUids ?? []).filter(
1429
+ (uid) => keepPartial.includes(uid) || !mailboxLabels.some((label) => label.uid === uid),
1430
+ );
1431
+ return { uid: message.uid, version: message.version, labelUids: [...new Set([...labelUids, ...kept])] };
1432
+ }),
1433
+ ),
1434
+ false,
1435
+ );
1436
+ }
1437
+
1438
+ function moveSelectionToType(type: Folder["type"], name: string) {
1439
+ void runBulkAction(async (chosen) => moveMessages(chosen, await resolveFolderOfType(type, name)), true);
1440
+ }
1441
+
1442
+ const loadMoreStatus = loadingMore ? (
1443
+ "Loading more\u2026"
1444
+ ) : loadMoreError ? (
1445
+ <span className="inline-flex items-center gap-2">
1446
+ <span role="alert" className="text-danger">
1447
+ {loadMoreError}
1448
+ </span>
1449
+ <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1450
+ Retry
1451
+ </button>
1452
+ </span>
1453
+ ) : loadMoreStalled ? (
1454
+ <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1455
+ Load more
1456
+ </button>
1457
+ ) : null;
1458
+
1459
+ function handleSelect(message: Message) {
1460
+ if (selectMode) {
1461
+ toggleSelected(message.uid);
1462
+ return;
1463
+ }
1464
+ if (isMobile) {
1465
+ window.location.href = `/messages/${encodeURIComponent(message.uid)}`;
1466
+ return;
1467
+ }
1468
+ setSelectedUid(message.uid);
1469
+ }
1470
+
1471
+ /** Opens a conversation in the reading pane, positioned at one of its messages: the one a child row
1472
+ * stands for, or the latest for a parent row. The thread pane loads the thread itself. */
1473
+ function handleOpenConversation(conversation: ConversationSummary, uid: string) {
1474
+ if (selectMode) {
1475
+ // Same rule as `handleSelect()` for a message row: while selecting, a row's own button ticks
1476
+ // the row rather than opening it.
1477
+ toggleConversationSelected(conversation);
1478
+ return;
1479
+ }
1480
+ if (isMobile) {
1481
+ // No dedicated mobile thread route yet - the existing single-message detail route already
1482
+ // handles any message uid regardless of conversation grouping.
1483
+ window.location.href = `/messages/${encodeURIComponent(uid)}`;
1484
+ return;
1485
+ }
1486
+ setSelectedUid(uid);
1487
+ setOpenThread({ conversation, uid });
1488
+ }
1489
+
1490
+ if (!folderUid && !aggregateFolderType) {
1491
+ // `MailShell` never renders this component at all until a mailbox is resolved (see its own
1492
+ // full-screen `MailboxProvisioning` takeover otherwise) — this is purely the brief gap before
1493
+ // that mailbox's own folder list has finished loading, not a "no mailbox" state. Distinct text
1494
+ // from the message list's own "Loading…" below — otherwise the two transient states become
1495
+ // indistinguishable to anything (a test, a user re-reading the screen) that catches this one.
1496
+ return <p className="p-8 text-sm text-text-muted">Loading your mailbox&hellip;</p>;
1497
+ }
1498
+
1499
+ return (
1500
+ <div className="flex h-full min-h-0">
1501
+ <div ref={scrollContainerRef} className="w-full md:w-96 shrink-0 md:border-r border-border overflow-y-auto">
1502
+ {selectMode ? (
1503
+ <MailSelectionBar
1504
+ selected={selectedMessages}
1505
+ listed={messages}
1506
+ totals={
1507
+ preferences.showAsConversations
1508
+ ? { selected: selectedConversationIds.size, listed: conversations.length, noun: "conversation" }
1509
+ : undefined
1510
+ }
1511
+ onSelectAll={() =>
1512
+ preferences.showAsConversations
1513
+ ? selectAllConversations()
1514
+ : setSelectedUids(new Set(messages.map((m) => m.uid)))
1515
+ }
1516
+ onClearSelection={() =>
1517
+ preferences.showAsConversations ? setSelectedConversationIds(new Set()) : setSelectedUids(new Set())
1518
+ }
1519
+ onCancel={leaveSelectMode}
1520
+ folders={currentFolders}
1521
+ currentFolderUid={folderUid}
1522
+ labels={mailboxLabels}
1523
+ mailboxUid={activeMailboxUid}
1524
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1525
+ onFolderCreated={onFolderCreated}
1526
+ onApplyLabels={applyLabelsToSelection}
1527
+ onSetRead={(read) => void runBulkAction((chosen) => setMessagesRead(chosen, read), false)}
1528
+ onSetFlagged={(flagged) => void runBulkAction((chosen) => setMessagesFlagged(chosen, flagged), false)}
1529
+ onArchive={() => void runBulkAction(bulkArchive, true)}
1530
+ onMoveTo={(targetFolderUid) => runBulkAction((chosen) => moveMessages(chosen, targetFolderUid), true)}
1531
+ onReportJunk={() => moveSelectionToType("junk", "Junk Email")}
1532
+ onDelete={() => moveSelectionToType("deleted_items", "Deleted Items")}
1533
+ busy={bulkBusy || resolvingSelection > 0}
1534
+ error={bulkError}
1535
+ />
1536
+ ) : (
1537
+ <MailListToolbar
1538
+ sortBy={preferences.sortBy}
1539
+ sortOrder={preferences.sortOrder}
1540
+ filter={preferences.filter}
1541
+ labelUids={preferences.labelUids}
1542
+ labels={mailboxLabels}
1543
+ mailboxUid={activeMailboxUid}
1544
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1545
+ onLabelUidsChange={(nextLabelUids) => updatePreferences({ labelUids: nextLabelUids })}
1546
+ showAsConversations={preferences.showAsConversations}
1547
+ onSortChange={(sortBy, sortOrder) => updatePreferences({ sortBy, sortOrder })}
1548
+ onFilterChange={(filter) => updatePreferences({ filter })}
1549
+ onShowAsConversationsChange={(showAsConversations) => updatePreferences({ showAsConversations })}
1550
+ selectMode={selectMode}
1551
+ onSelectModeChange={setSelectMode}
1552
+ offerClassificationFilters={offerClassificationFilters}
1553
+ filterDisabled={isSearching}
1554
+ filterDisabledReason="Filters don't apply to search results"
1555
+ sortKeysDisabled={isSearching || !!aggregateFolderType}
1556
+ // A conversation row is a thread summary, so only some of the keys have anything to
1557
+ // order by - the rest stay pickable and are applied to the rows already fetched.
1558
+ unavailableSortKeys={preferences.showAsConversations ? CONVERSATION_SORT_UNAVAILABLE : undefined}
1559
+ sortKeysNote={
1560
+ isSearching
1561
+ ? "Search results are ranked by relevance rather than sorted."
1562
+ : aggregateFolderType
1563
+ ? "This view merges the newest mail from every mailbox and is always listed by date."
1564
+ : preferences.showAsConversations
1565
+ ? CONVERSATION_SORT_NOTE
1566
+ : undefined
1567
+ }
1568
+ selectDisabled={!!aggregateFolderType || loading || listedRowCount === 0}
1569
+ selectDisabledReason={
1570
+ aggregateFolderType
1571
+ ? "Open a mailbox's own folder to select messages"
1572
+ : loading
1573
+ ? "Wait for this folder to finish loading"
1574
+ : "There is nothing here to select"
1575
+ }
1576
+ />
1577
+ )}
1578
+ {!preferences.showAsConversations && (
1579
+ <div className="p-2 border-b border-border">
1580
+ <input
1581
+ type="search"
1582
+ value={searchInput}
1583
+ onChange={(e) => setSearchInput(e.target.value)}
1584
+ placeholder={aggregateFolderType ? "Open a mailbox's own folder to search" : "Search all mail…"}
1585
+ aria-label="Search all mail"
1586
+ disabled={!!aggregateFolderType}
1587
+ className="w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface disabled:opacity-55"
1588
+ />
1589
+ </div>
1590
+ )}
1591
+ {/* Two tabs, as Outlook has: Focused and Other. There is no "All" tab - the whole Inbox is
1592
+ still one pick away, in the Filter menu, which is where every other named filter lives
1593
+ and the only place that can show which of them is really in force. A stored `all` (or
1594
+ Unread, Flagged, ...) therefore still lists what it always did, with neither tab
1595
+ pressed, rather than being migrated into one of these two halves behind the reader's
1596
+ back - see `MAIL_LIST_FILTERS`, which still offers it. */}
1597
+ {offerClassificationFilters && (
1598
+ <div className="flex border-b border-border text-xs">
1599
+ {MAIL_LIST_CLASSIFICATION_FILTERS.map(({ value, label }) => (
1600
+ <button
1601
+ key={value}
1602
+ type="button"
1603
+ aria-pressed={preferences.filter === value}
1604
+ onClick={() => updatePreferences({ filter: value })}
1605
+ className={[
1606
+ "flex-1 py-1.5 font-semibold",
1607
+ preferences.filter === value
1608
+ ? "text-primary-dark border-b-2 border-primary-dark"
1609
+ : "text-text-muted",
1610
+ ].join(" ")}
1611
+ >
1612
+ {label}
1613
+ </button>
1614
+ ))}
1615
+ </div>
1616
+ )}
1617
+
1618
+ {isSearching && (
1619
+ <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border flex items-center justify-between gap-2">
1620
+ {/* §_Progressive Results_: "Never show a hard count until every tier has reported.
1621
+ Display n of ??, or omit the count. A settled count is the signal that ordering
1622
+ is final." */}
1623
+ <span>
1624
+ {tier1Done && tier2Done && tier3Done
1625
+ ? `${messages.length} result${messages.length === 1 ? "" : "s"}`
1626
+ : `${messages.length} of ??`}
1627
+ </span>
1628
+ {tier2Done && !searchAllMail && (
1629
+ <button
1630
+ type="button"
1631
+ onClick={handleSearchAllMail}
1632
+ className="text-primary-dark hover:underline font-medium shrink-0"
1633
+ >
1634
+ Search all mail
1635
+ </button>
1636
+ )}
1637
+ </div>
1638
+ )}
1639
+ {isSearching && coverage?.indexedFrom && (
1640
+ <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border">
1641
+ Local search covers messages back to {new Date(coverage.indexedFrom).toLocaleDateString()}
1642
+ {coverage.building ? " (still building)" : ""}
1643
+ {searchAllMail
1644
+ ? " - searching everything, not just recent mail."
1645
+ : " - older encrypted mail is still searched, just slower."}
1646
+ </div>
1647
+ )}
1648
+ {isSearching && !getUnlockedKeys(mailboxUid!) && (
1649
+ <div className="px-4 py-2 border-b border-border bg-surface-alt">
1650
+ <button
1651
+ type="button"
1652
+ onClick={handleUnlockSearch}
1653
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1654
+ >
1655
+ <HiOutlineLockClosed size={12} aria-hidden="true" />
1656
+ Unlock to include encrypted messages in these results
1657
+ </button>
1658
+ </div>
1659
+ )}
1660
+ {!isSearching && !preferences.showAsConversations && undecryptedEncryptedUids.length > 0 && !getUnlockedKeys(activeMailboxUid) && (
1661
+ <div className="px-4 py-2 border-b border-border bg-surface-alt">
1662
+ <button
1663
+ type="button"
1664
+ onClick={handleUnlockList}
1665
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1666
+ >
1667
+ <HiOutlineLockClosed size={12} aria-hidden="true" />
1668
+ Unlock to show {undecryptedEncryptedUids.length === 1 ? "an encrypted message's" : "encrypted messages'"} subject
1669
+ </button>
1670
+ </div>
1671
+ )}
1672
+
1673
+ {error && (
1674
+ <div className="p-4">
1675
+ <Alert>{error}</Alert>
1676
+ </div>
1677
+ )}
1678
+
1679
+ {loading ? (
1680
+ <p className="p-4 text-sm text-text-muted">Loading&hellip;</p>
1681
+ ) : preferences.showAsConversations ? (
1682
+ <>
1683
+ <ConversationList
1684
+ conversations={listedConversations}
1685
+ newestFirst={preferences.sortBy === "date" && preferences.sortOrder === "desc"}
1686
+ mailboxUid={activeMailboxUid}
1687
+ selectedUid={selectedUid}
1688
+ messageOverrides={conversationPatches}
1689
+ onOpenMessage={handleOpenConversation}
1690
+ selectMode={selectMode}
1691
+ selectedConversationIds={selectedConversationIds}
1692
+ onToggleSelected={toggleConversationSelected}
1693
+ />
1694
+ {hasMore && (
1695
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1696
+ {loadMoreStatus}
1697
+ </div>
1698
+ )}
1699
+ </>
1700
+ ) : messages.length === 0 ? (
1701
+ <>
1702
+ <p className="p-4 text-sm text-text-muted">
1703
+ {isSearching
1704
+ ? `No messages match "${searchQuery}".`
1705
+ : effectiveFilter === "all"
1706
+ ? "No messages in this folder."
1707
+ : "No messages here."}
1708
+ </p>
1709
+ {/* Still offered while a filter hides every loaded row - what it's looking for may be
1710
+ on a later page. */}
1711
+ {hasMore && (
1712
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1713
+ {loadMoreStatus}
1714
+ </div>
1715
+ )}
1716
+ </>
1717
+ ) : (
1718
+ <>
1719
+ <ul>
1720
+ {messages.map((message) => (
1721
+ <li key={message.uid} className="flex items-stretch border-b border-border">
1722
+ {selectMode && (
1723
+ <span className="shrink-0 flex items-center pl-3">
1724
+ <input
1725
+ type="checkbox"
1726
+ checked={selectedUids.has(message.uid)}
1727
+ onChange={() => toggleSelected(message.uid)}
1728
+ aria-label={`Select ${rowSubject(message)}`}
1729
+ className="w-4 h-4 accent-primary"
1730
+ />
1731
+ </span>
1732
+ )}
1733
+ <button
1734
+ type="button"
1735
+ onClick={() => handleSelect(message)}
1736
+ className={[
1737
+ "flex-1 min-w-0 text-left px-4 py-3",
1738
+ message.uid === selectedUid || selectedUids.has(message.uid)
1739
+ ? "bg-primary/10"
1740
+ : "hover:bg-surface-alt",
1741
+ message.flags.read ? "" : "font-semibold",
1742
+ ].join(" ")}
1743
+ >
1744
+ <div className="flex items-center justify-between gap-2 text-sm">
1745
+ <span className="truncate">{message.from.displayName || message.from.address}</span>
1746
+ <span className="text-xs text-text-muted shrink-0">
1747
+ {new Date(message.receivedDate).toLocaleDateString()}
1748
+ </span>
1749
+ </div>
1750
+ {aggregateFolderType && (
1751
+ // The one view where a row needs to say which mailbox it came from.
1752
+ <div className="text-xs text-text-muted truncate font-normal">
1753
+ {mailboxes.find((mb) => mb.uid === message.mailboxUid)?.displayName}
1754
+ </div>
1755
+ )}
1756
+ {isSearching && pendingUids.has(message.uid) ? (
1757
+ // §_Progressive Results_: "Unresolved encrypted results MUST
1758
+ // be rendered as skeleton entries in place, not appended on
1759
+ // arrival." This uid is a Tier 1 metadataOnly guess Tier 2/3
1760
+ // haven't confirmed (or ruled out) yet.
1761
+ <div className="flex flex-col gap-1.5 py-0.5">
1762
+ <Skeleton height="h-3.5" className="w-2/3 rounded-sm" />
1763
+ <Skeleton height="h-3" className="w-full rounded-sm" />
1764
+ </div>
1765
+ ) : (
1766
+ <>
1767
+ <div className="text-sm truncate">{rowSubject(message)}</div>
1768
+ <div className="flex items-center gap-2 text-xs text-text-muted font-normal">
1769
+ <span className="truncate">
1770
+ {snippets[message.uid] || decryptedRows[message.uid]?.preview || message.bodyPreview}
1771
+ </span>
1772
+ {message.hasAttachments && <HiOutlinePaperClip size={12} aria-label="Has attachments" />}
1773
+ {message.flags.flagged && (
1774
+ <HiOutlineFlag size={12} aria-label="Flagged" className="text-danger" />
1775
+ )}
1776
+ </div>
1777
+ </>
1778
+ )}
1779
+ </button>
1780
+ </li>
1781
+ ))}
1782
+ </ul>
1783
+ {hasMore && (
1784
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1785
+ {loadMoreStatus}
1786
+ </div>
1787
+ )}
1788
+ {aggregateFolderType && (
1789
+ <p className="p-4 text-center text-xs text-text-muted">
1790
+ Showing the most recent mail from each mailbox. Open a specific mailbox&rsquo;s folder to
1791
+ see older mail.
1792
+ </p>
1793
+ )}
1794
+ </>
1795
+ )}
1796
+ </div>
1797
+ {/* The reading pane's own height: a row of the full-height mail view, stretched to it by the
1798
+ flex chain rather than by a percentage (an explicit height would opt it out of that
1799
+ stretching), with `min-h-0` so a long message scrolls inside it instead of pushing it past
1800
+ the window. Everything below - the thread pane, each message's `MessageDetailPane`, the
1801
+ body iframe that cannot measure itself - takes its height from here, never from a `vh`
1802
+ number of its own. */}
1803
+ <div className="hidden md:flex flex-1 min-w-0 min-h-0">
1804
+ {preferences.showAsConversations ? (
1805
+ <ConversationThreadPane
1806
+ conversation={openThread?.conversation ?? null}
1807
+ selectedUid={openThread?.uid ?? null}
1808
+ mailboxUid={activeMailboxUid}
1809
+ folders={currentFolders}
1810
+ labels={mailboxLabels}
1811
+ onMessagePatched={patchListedMessage}
1812
+ onMessageRemoved={(updated) => removeListedMessage(updated.uid)}
1813
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1814
+ onFolderCreated={onFolderCreated}
1815
+ />
1816
+ ) : (
1817
+ <MessageDetailPane
1818
+ message={selected}
1819
+ attachments={attachments}
1820
+ isSentItems={isSentItems}
1821
+ onRecalled={patchListedMessage}
1822
+ isOutbox={isOutbox}
1823
+ onReceiptHandled={patchListedMessage}
1824
+ draftsFolderUid={draftsFolderUid}
1825
+ folders={folders}
1826
+ onMoved={(updated) => {
1827
+ // Same reasoning as onArchived below - a move takes the message out of the folder
1828
+ // being listed, so it leaves the list rather than being patched in place.
1829
+ removeListedMessage(updated.uid);
1830
+ }}
1831
+ onFolderCreated={onFolderCreated}
1832
+ onScheduledSendCanceled={(updated) => {
1833
+ // The message moved out of the currently-viewed Outbox folder (into Drafts)
1834
+ // - unlike a recall, which patches a message in place, this removes it from
1835
+ // the list entirely, matching what a real folder switch would show.
1836
+ removeListedMessage(updated.uid);
1837
+ }}
1838
+ onArchived={(updated) => {
1839
+ // Same reasoning as onScheduledSendCanceled above - the message moved out of
1840
+ // whichever folder is currently being viewed (into Archive), so it's removed
1841
+ // from the list rather than patched in place.
1842
+ removeListedMessage(updated.uid);
1843
+ }}
1844
+ labels={labels}
1845
+ onLabelsChanged={patchListedMessage}
1846
+ onLabelCreated={(label) =>
1847
+ (otherMailbox ? setOtherMailboxLabels : setMailboxLabels)((prev) => [...prev, label])
1848
+ }
1849
+ />
1850
+ )}
1851
+ </div>
1852
+ </div>
1853
+ );
1854
+ }