@rapidmx/web-client 0.3.0 → 0.4.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 (102) hide show
  1. package/apps/admin/branding/index.tsx +39 -404
  2. package/apps/admin/domains/[uid].tsx +92 -259
  3. package/apps/admin/encryption-policy/index.tsx +19 -0
  4. package/apps/admin/index.tsx +100 -82
  5. package/apps/admin/mailbox-policy/index.tsx +19 -0
  6. package/apps/admin/mailboxes/new/index.tsx +28 -291
  7. package/apps/admin/plugins/index.tsx +15 -0
  8. package/apps/admin/retention-policy/index.tsx +39 -132
  9. package/apps/admin/setup/index.tsx +15 -0
  10. package/apps/shared/components/admin/layout/AdminShell.tsx +249 -210
  11. package/apps/shared/components/admin/settings/BrandingForm.tsx +374 -0
  12. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +176 -0
  13. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +104 -0
  14. package/apps/shared/components/admin/settings/LoadedSettingsForm.tsx +34 -0
  15. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +302 -0
  16. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +119 -0
  17. package/apps/shared/components/admin/settings/PluginsManager.tsx +595 -0
  18. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +98 -0
  19. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +254 -0
  20. package/apps/shared/components/admin/setup/SetupWizard.tsx +300 -0
  21. package/apps/shared/components/calendar/CalendarListSidebar.tsx +120 -76
  22. package/apps/shared/components/calendar/EventModal.tsx +40 -4
  23. package/apps/shared/components/calendar/layout/CalendarShell.tsx +80 -99
  24. package/apps/shared/components/contacts/ContactForm.tsx +38 -4
  25. package/apps/shared/components/layout/AppShell.tsx +198 -169
  26. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +298 -265
  27. package/apps/shared/components/layout/UnlockPromptProvider.tsx +128 -0
  28. package/apps/shared/components/mail/MessageDetailPane.tsx +630 -595
  29. package/apps/shared/components/mail/compose/ComposeContext.tsx +8 -3
  30. package/apps/shared/components/mail/compose/ComposeWindow.tsx +930 -765
  31. package/apps/shared/components/mail/layout/MailShell.tsx +408 -302
  32. package/apps/shared/components/settings/layout/SettingsShell.tsx +1 -0
  33. package/apps/shared/mail/findWellKnownFolderUid.ts +13 -0
  34. package/apps/shared/search/LocalIndexLifecycle.tsx +89 -0
  35. package/apps/shared/search/localIndexBlockCipher.ts +83 -0
  36. package/apps/shared/search/localIndexBuilder.ts +179 -0
  37. package/apps/shared/search/localIndexKey.ts +27 -0
  38. package/apps/shared/search/localIndexRpcClient.ts +116 -0
  39. package/apps/shared/search/localIndexSchema.ts +227 -0
  40. package/apps/shared/search/localIndexSizePreference.ts +88 -0
  41. package/apps/shared/search/localIndexVFS.ts +235 -0
  42. package/apps/shared/search/localIndexWorker.ts +464 -0
  43. package/apps/shared/search/searchTier2.ts +79 -0
  44. package/apps/shared/search/wa-sqlite-shims.d.ts +44 -0
  45. package/apps/www/calendar/index.tsx +31 -21
  46. package/apps/www/contacts/index.tsx +33 -6
  47. package/apps/www/index.tsx +661 -106
  48. package/apps/www/messages/[uid].tsx +5 -1
  49. package/apps/www/settings/encryption/index.tsx +63 -1
  50. package/apps/www/settings/sharing/index.tsx +271 -0
  51. package/apps/www/tasks/index.tsx +53 -4
  52. package/dist/apps/admin/branding/index.js +4 -98
  53. package/dist/apps/admin/domains/[uid].js +5 -68
  54. package/dist/apps/admin/encryption-policy/index.js +8 -0
  55. package/dist/apps/admin/index.js +14 -1
  56. package/dist/apps/admin/mailbox-policy/index.js +8 -0
  57. package/dist/apps/admin/mailboxes/new/index.js +4 -89
  58. package/dist/apps/admin/plugins/index.js +6 -0
  59. package/dist/apps/admin/retention-policy/index.js +3 -36
  60. package/dist/apps/admin/setup/index.js +6 -0
  61. package/dist/apps/shared/components/admin/layout/AdminShell.js +34 -3
  62. package/dist/apps/shared/components/admin/settings/BrandingForm.js +105 -0
  63. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +77 -0
  64. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +57 -0
  65. package/dist/apps/shared/components/admin/settings/LoadedSettingsForm.js +25 -0
  66. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +106 -0
  67. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +52 -0
  68. package/dist/apps/shared/components/admin/settings/PluginsManager.js +260 -0
  69. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +44 -0
  70. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +131 -0
  71. package/dist/apps/shared/components/admin/setup/SetupWizard.js +142 -0
  72. package/dist/apps/shared/components/calendar/CalendarListSidebar.js +24 -13
  73. package/dist/apps/shared/components/calendar/EventModal.js +16 -4
  74. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +47 -39
  75. package/dist/apps/shared/components/contacts/ContactForm.js +16 -5
  76. package/dist/apps/shared/components/layout/AppShell.js +30 -7
  77. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +15 -3
  78. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +77 -0
  79. package/dist/apps/shared/components/mail/MessageDetailPane.js +27 -2
  80. package/dist/apps/shared/components/mail/compose/ComposeContext.js +2 -2
  81. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +134 -14
  82. package/dist/apps/shared/components/mail/layout/MailShell.js +106 -40
  83. package/dist/apps/shared/components/settings/layout/SettingsShell.js +1 -0
  84. package/dist/apps/shared/mail/findWellKnownFolderUid.js +12 -0
  85. package/dist/apps/shared/search/LocalIndexLifecycle.js +76 -0
  86. package/dist/apps/shared/search/localIndexBlockCipher.js +63 -0
  87. package/dist/apps/shared/search/localIndexBuilder.js +153 -0
  88. package/dist/apps/shared/search/localIndexKey.js +25 -0
  89. package/dist/apps/shared/search/localIndexRpcClient.js +78 -0
  90. package/dist/apps/shared/search/localIndexSchema.js +179 -0
  91. package/dist/apps/shared/search/localIndexSizePreference.js +78 -0
  92. package/dist/apps/shared/search/localIndexVFS.js +230 -0
  93. package/dist/apps/shared/search/localIndexWorker.js +341 -0
  94. package/dist/apps/shared/search/searchTier2.js +38 -0
  95. package/dist/apps/www/calendar/index.js +14 -12
  96. package/dist/apps/www/contacts/index.js +15 -6
  97. package/dist/apps/www/index.js +496 -94
  98. package/dist/apps/www/messages/[uid].js +5 -1
  99. package/dist/apps/www/settings/encryption/index.js +30 -2
  100. package/dist/apps/www/settings/sharing/index.js +128 -0
  101. package/dist/apps/www/tasks/index.js +27 -5
  102. package/package.json +3 -2
@@ -4,36 +4,104 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
4
4
  // SPDX-License-Identifier: MPL-2.0
5
5
  ///////////////////////////////////////////////////////////////////////////////
6
6
  import { useCallback, useEffect, useRef, useState } from "react";
7
+ import { HiOutlineLockClosed } from "react-icons/hi2";
7
8
  import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
- import { getMessage, listMessages } from "@rapidmx/react-shared/mail/mailApi.js";
9
+ import { getMessage, getMessageRawContent, listMessages } from "@rapidmx/react-shared/mail/mailApi.js";
9
10
  import { listLabels } from "@rapidmx/react-shared/mail/labelsApi.js";
10
11
  import { listConversations } from "@rapidmx/react-shared/mail/conversationsApi.js";
11
12
  import { search as searchMailbox } from "@rapidmx/react-shared/search/searchApi.js";
12
13
  import { parseSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
13
14
  import { normalizeServerScores } from "@rapidmx/react-shared/search/searchScoring.js";
14
15
  import { searchEncryptedCandidates } from "@rapidmx/react-shared/search/searchTier3.js";
16
+ import { searchLocalIndex } from "../shared/search/searchTier2.js";
15
17
  import { getUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
18
+ import { evaluateMessageSecurity } from "@rapidmx/react-shared/crypto/messageSecurity.js";
16
19
  import { useMarkMessageRead, useMessageAttachments } from "@rapidmx/react-shared/mail/mailDetailHooks.js";
17
20
  import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
18
- import MailShell, { useMailShell } from "../shared/components/mail/layout/MailShell.js";
21
+ import MailShell, { useMailShell, } from "../shared/components/mail/layout/MailShell.js";
19
22
  import MessageDetailPane from "../shared/components/mail/MessageDetailPane.js";
20
23
  import ConversationList from "../shared/components/mail/ConversationList.js";
21
24
  import ConversationThreadPane from "../shared/components/mail/ConversationThreadPane.js";
22
25
  import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
26
+ import Skeleton from "@rapidmx/react-shared/components/feedback/Skeleton.js";
27
+ import { useUnlockPrompt } from "../shared/components/layout/UnlockPromptProvider.js";
23
28
  const MESSAGE_PAGE_SIZE = 50;
24
29
  const SEARCH_DEBOUNCE_MS = 300;
25
- /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message) and Tier 3 (decrypted,
26
- * content-verified) results into one ranked list, per `specs/search.md` §7's "client MUST re-score all
27
- * results it can see... normalise into the same space rather than interleaving raw scores": both sides
28
- * are normalized independently via `normalizeServerScores()` before merging, since a Postgres/OpenSearch
29
- * score and this module's own term-count score occupy unrelated ranges. A uid present in both lists
30
- * (Tier 1 found it via a `participants` coincidence, Tier 3 then genuinely verified its content) keeps
31
- * only the Tier 3 entry - real content verification supersedes a metadata guess for the same message.
32
- * Deliberately not the spec's full skeleton/reordering "Progressive Results" UX (§_Progressive
33
- * Results_) - that's real, separate UI work; this returns one final merged list once both tiers
34
- * resolve, same as how the search box already waits on one round-trip today. */
35
- function mergeSearchResults(tier1, tier3) {
30
+ const LIST_PREVIEW_MAX_LENGTH = 160;
31
+ /** The literal outer-envelope `Subject` every encrypted message carries server-side - RFC 9788's
32
+ * `hcp_baseline` policy obscures it to this exact string (see `smimeMessage.ts`'s
33
+ * `applyBaselineOuterHeaders()`), which is also all `Message.subject` ever shows for one of these until
34
+ * decrypted client-side. Used here to recognize which loaded rows are worth decrypting for display. */
35
+ const ENCRYPTED_SUBJECT_PLACEHOLDER = "[...]";
36
+ /** Strips HTML down to plain text, for a short list-row preview of a decrypted body - mirrors
37
+ * `searchTier3.ts`'s own private `stripHtml()` (not currently exported from `@rapidmx/react-shared`,
38
+ * so duplicated here rather than pulled in through a package change just for this one small, pure
39
+ * helper). Not a security boundary - the output only ever feeds plain text display, truncated below,
40
+ * never rendered back into any DOM. */
41
+ function stripHtmlToText(html) {
42
+ return html
43
+ .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ")
44
+ .replace(/<[^>]+>/g, " ")
45
+ .replace(/&nbsp;/gi, " ")
46
+ .replace(/&amp;/gi, "&")
47
+ .replace(/&lt;/gi, "<")
48
+ .replace(/&gt;/gi, ">")
49
+ .replace(/&quot;/gi, '"')
50
+ .replace(/&#0*39;/gi, "'")
51
+ .replace(/\s+/g, " ")
52
+ .trim();
53
+ }
54
+ /**
55
+ * Decrypts the subject/preview of every currently-loaded row whose subject is still the RFC 9788
56
+ * placeholder (i.e. every encrypted message this device hasn't already resolved), keyed by uid - the
57
+ * inbox-list counterpart to `MessageDetailPane`'s own single-message decrypt and `searchTier3.ts`'s
58
+ * per-candidate decrypt. Bounded to `messages` (at most one loaded page, `MESSAGE_PAGE_SIZE`), never the
59
+ * whole mailbox - matching `searchEncryptedCandidates()`'s own "bounded, not everything" scope. Runs only
60
+ * once `unlocked` is available (the caller decides when to call this - see `InboxContent`'s own effect
61
+ * and `handleUnlockList()`), and a single row's fetch/decrypt failure never blocks the rest.
62
+ */
63
+ async function decryptEncryptedRows(messages, unlocked) {
64
+ const encrypted = messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER);
65
+ const entries = await Promise.all(encrypted.map(async (message) => {
66
+ try {
67
+ const rawMime = await getMessageRawContent(message.uid);
68
+ const security = await evaluateMessageSecurity(rawMime, unlocked);
69
+ if (!security.subject && !security.html) {
70
+ return null;
71
+ }
72
+ const preview = security.html ? stripHtmlToText(security.html).slice(0, LIST_PREVIEW_MAX_LENGTH) : undefined;
73
+ return [message.uid, { subject: security.subject, preview }];
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ }));
79
+ const result = {};
80
+ for (const entry of entries) {
81
+ if (entry) {
82
+ result[entry[0]] = entry[1];
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+ /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message), Tier 2 (local index, fully
88
+ * decrypted and re-scored), and Tier 3 (server-narrowed candidates, decrypted and re-scored) results into
89
+ * one ranked list, per `specs/search.md` §7's "client MUST re-score all results it can see... normalise
90
+ * into the same space rather than interleaving raw scores": each tier is normalized independently via
91
+ * `normalizeServerScores()` before merging, since a Postgres/OpenSearch score, a local `bm25()` score,
92
+ * and this module's own Tier 3 term-count score all occupy unrelated ranges. A uid present in more than
93
+ * one list keeps only the last-inserted entry (Tier 2 wins over Tier 3 wins over Tier 1) - Tier 2 and
94
+ * Tier 3 both represent genuine, content-verified scores for the same message, so which one "wins" on
95
+ * overlap doesn't change correctness, only which of two equally-valid scores is shown; either supersedes
96
+ * Tier 1's metadata-only guess for the same uid.
97
+ *
98
+ * Called progressively - once per tier as it resolves, each time with whatever tiers have reported so
99
+ * far (an empty array for the rest) - by `InboxContent`'s own search orchestration below, per §_Progressive
100
+ * Results_' "reordering is permitted and preferred over appending." This function itself stays pure and
101
+ * stateless; it has no notion of "in progress" versus "final." */
102
+ function mergeSearchResults(tier1, tier2, tier3) {
36
103
  const normalizedTier1 = normalizeServerScores(tier1);
104
+ const normalizedTier2 = normalizeServerScores(tier2);
37
105
  const normalizedTier3 = normalizeServerScores(tier3);
38
106
  const merged = new Map();
39
107
  for (const entry of normalizedTier1) {
@@ -42,75 +110,159 @@ function mergeSearchResults(tier1, tier3) {
42
110
  for (const entry of normalizedTier3) {
43
111
  merged.set(entry.result.entityUid, entry);
44
112
  }
113
+ for (const entry of normalizedTier2) {
114
+ merged.set(entry.result.entityUid, entry);
115
+ }
45
116
  return Array.from(merged.values())
46
117
  .sort((a, b) => b.normalizedScore - a.normalizedScore)
47
118
  .map((entry) => entry.result);
48
119
  }
49
- /** Resolves one page of search hits into full `Message` records for display, plus each hit's own
50
- * `snippet` (keyed by message uid) for rendering in place of the plain `bodyPreview` while searching.
51
- *
52
- * `rawQuery` is parsed once, client-side, via `queryGrammar.ts`'s `parseSearchQuery()` — the operator
53
- * grammar (`from:`/`to:`/`subject:`/`has:attachment`/`before:`/`after:`/`in:`/`is:`/`label:`/`type:`,
54
- * `specs/search.md` §14) is extracted into structured filters passed to the server, while the
55
- * remaining free text (quotes, `-` negation, `OR` all preserved) still drives ranking as `q`.
56
- * `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
120
+ /** `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
57
121
  * (contact/calendarEvent/note/task) has no `Message` to resolve via `getMessage()` below and is simply
58
122
  * dropped by the same eventually-consistent-index fallback that already existed, rather than rendered
59
123
  * (this inbox list only ever shows message rows; a real multi-entity-type results view is a separate,
60
- * larger UI project outside this pass).
124
+ * larger UI project outside this pass). Shared by both the fresh-search orchestration and `loadMore()`
125
+ * below, which each build this from the same `ParsedSearchQuery` differently only in `cursor`. */
126
+ function tier1SearchParams(parsed, cursor) {
127
+ return {
128
+ types: parsed.entityTypes ?? ["message"],
129
+ cursor,
130
+ limit: MESSAGE_PAGE_SIZE,
131
+ from: parsed.from,
132
+ to: parsed.to,
133
+ cc: parsed.cc,
134
+ subject: parsed.subject,
135
+ hasAttachment: parsed.hasAttachment,
136
+ before: parsed.before,
137
+ after: parsed.after,
138
+ folderUid: parsed.folderUid,
139
+ flags: parsed.flags,
140
+ labels: parsed.labels,
141
+ };
142
+ }
143
+ /** How many of Tier 1's own `metadataOnly` hits (§7: "an encrypted entity matched only on server-visible
144
+ * metadata... MUST be rendered as skeleton entries in place... using the metadata score as a provisional
145
+ * position") are shown as skeleton rows at once - §_Progressive Results_' "Skeletons MUST be capped, at
146
+ * approximately one and a half pages." A non-`metadataOnly` Tier 1 hit (a real, already-scored content
147
+ * match — always the case for unencrypted mail) is never a skeleton and is never subject to this cap.
61
148
  *
62
- * Tier 3 (`searchTier3.ts#searchEncryptedCandidates()`) runs alongside Tier 1 only for the first page
63
- * (`cursor` absent) - it has no pagination wiring yet (a deliberate scope trim, see that module's own
64
- * doc comment), so a `loadMore()` continuation stays Tier-1-only. Silently contributes nothing when
65
- * this mailbox has no unlocked keys this session (`getUnlockedKeys()` returns `undefined`) - nothing
66
- * for it to decrypt, same as `MessageDetailPane`'s own encrypted-message handling elsewhere. */
67
- async function searchMessages(mailboxUid, rawQuery, cursor) {
68
- const parsed = parseSearchQuery(rawQuery);
69
- const [page, tier3Results] = await Promise.all([
70
- searchMailbox(parsed.text, {
71
- types: parsed.entityTypes ?? ["message"],
72
- cursor,
73
- limit: MESSAGE_PAGE_SIZE,
74
- from: parsed.from,
75
- to: parsed.to,
76
- cc: parsed.cc,
77
- subject: parsed.subject,
78
- hasAttachment: parsed.hasAttachment,
79
- before: parsed.before,
80
- after: parsed.after,
81
- folderUid: parsed.folderUid,
82
- flags: parsed.flags,
83
- labels: parsed.labels,
84
- }),
85
- cursor ? Promise.resolve([]) : searchEncryptedCandidates(parsed, getUnlockedKeys(mailboxUid)),
86
- ]);
87
- const mergedResults = mergeSearchResults(page.results, tier3Results);
88
- const resolved = await Promise.all(mergedResults.map(async (hit) => {
149
+ * A Tier 3 candidate that Tier 1 did *not* already surface has no provisional score/position of its own
150
+ * under the spec's own wording above, so it is deliberately never pre-rendered as a skeleton here either
151
+ * - it simply appears, fully resolved, once Tier 3 confirms it (see `InboxContent`'s search
152
+ * orchestration). */
153
+ const SKELETON_CAP = Math.round(MESSAGE_PAGE_SIZE * 1.5);
154
+ function capSkeletons(tier1Hits) {
155
+ let skeletonsSeen = 0;
156
+ return tier1Hits.filter((hit) => {
157
+ if (!hit.metadataOnly) {
158
+ return true;
159
+ }
160
+ skeletonsSeen += 1;
161
+ return skeletonsSeen <= SKELETON_CAP;
162
+ });
163
+ }
164
+ /** How many candidates Tier 3 pulls per distinct search - larger than one page's worth so several
165
+ * `loadMore()` pages can be sliced from one decrypt pass (see `Tier3Cache` below) instead of a second,
166
+ * separately expensive server round trip and re-decrypt for the same query. Bounded, not unlimited - per
167
+ * this module's own `tier1SearchParams()` sibling, Tier 3's own candidate-narrowing is already the
168
+ * "heaviest single client-side cost" tier (`specs/search.md` §9's identical framing for attachment
169
+ * extraction); a query whose true candidate set exceeds this simply pages out once this cache is
170
+ * exhausted; `loadMore()` reflects that honestly via `hasMore`. */
171
+ const TIER3_CANDIDATE_LIMIT = 200;
172
+ function tier3CacheKey(mailboxUid, fingerprint, searchAllMail, unlocked) {
173
+ return `${mailboxUid}|${fingerprint}|${String(searchAllMail)}|${String(unlocked)}`;
174
+ }
175
+ /** A search query's cache/cursor identity - stable across re-parsing the identical raw text, and
176
+ * distinct for anything else (§8's "a query fingerprint, so a cursor cannot be replayed against a
177
+ * different query"). `JSON.stringify` on `ParsedSearchQuery` is deterministic here because every one of
178
+ * its own fields is a primitive or a `Date` (which serializes to a fixed ISO string) - no nested object
179
+ * whose key order could vary between two structurally-identical parses of the same text. */
180
+ function queryFingerprint(parsed) {
181
+ return JSON.stringify(parsed);
182
+ }
183
+ /** Tier 3's own `before` bound, tightened to Tier 2's already-covered window (`coverage.indexedFrom`)
184
+ * unless the reader explicitly asked to "Search all mail" - Tier 2 already holds fully-decrypted,
185
+ * current content for everything at least that recent, so re-fetching and re-decrypting the same range
186
+ * through Tier 3's slower candidate-narrowing path would be pure waste. Never *widens* an existing
187
+ * `before:` the query already specified. */
188
+ function tightenBeforeToCoverage(parsed, coverage, searchAllMail) {
189
+ if (searchAllMail || !coverage?.indexedFrom) {
190
+ return parsed;
191
+ }
192
+ const coverageBound = new Date(coverage.indexedFrom);
193
+ const effectiveBefore = parsed.before && parsed.before.getTime() < coverageBound.getTime() ? parsed.before : coverageBound;
194
+ return { ...parsed, before: effectiveBefore };
195
+ }
196
+ /** `undefined` for a missing, corrupted, or foreign-query cursor - every caller already treats "no
197
+ * cursor" as "start this tier from the beginning," so there's no separate error path needed here. */
198
+ function decodeCursor(raw, fingerprint) {
199
+ return raw?.fingerprint === fingerprint ? raw : undefined;
200
+ }
201
+ /** Resolves every hit's `entityUid` to a full `Message` via `getMessage()`, reusing `cache` across
202
+ * repeated calls within the same search pass - `InboxContent`'s own search orchestration below re-merges
203
+ * and re-resolves the *entire* current hit set each time a tier resolves, so without this cache every
204
+ * stage would re-fetch messages an earlier stage already fetched. A hit whose message no longer resolves
205
+ * (deleted after being indexed, or the fetch itself failed) is cached as `null` and dropped - the same
206
+ * "a search hit can briefly outlive the message it points to" tolerance this function's inline
207
+ * predecessor already had. */
208
+ async function resolveHitsToMessages(hits, cache) {
209
+ const toFetch = hits.filter((hit) => !cache.has(hit.entityUid));
210
+ await Promise.all(toFetch.map(async (hit) => {
89
211
  const message = await getMessage(hit.entityUid).catch(() => null);
90
- return message ? { message, snippet: hit.snippet } : null;
212
+ cache.set(hit.entityUid, message);
91
213
  }));
92
- // A search hit can briefly outlive the message it points to (index updates are eventually consistent,
93
- // and a message can be deleted after being indexed) - drop anything that no longer resolves rather than
94
- // rendering a broken entry.
95
214
  const messages = [];
96
215
  const snippets = {};
97
- for (const entry of resolved) {
98
- if (!entry) {
216
+ for (const hit of hits) {
217
+ const message = cache.get(hit.entityUid);
218
+ if (!message) {
99
219
  continue;
100
220
  }
101
- messages.push(entry.message);
102
- if (entry.snippet) {
103
- snippets[entry.message.uid] = entry.snippet;
221
+ messages.push(message);
222
+ if (hit.snippet) {
223
+ snippets[message.uid] = hit.snippet;
104
224
  }
105
225
  }
106
- return { messages, nextCursor: page.nextCursor, snippets };
226
+ return { messages, snippets };
227
+ }
228
+ /** Flattens and sorts a per-mailbox fetch into one merged, newest-first list - the aggregate ("All
229
+ * Inboxes" etc.) equivalent of `mergeSearchResults()` above, but simpler: an aggregated message has no
230
+ * natural relevance score to normalize, so this only ever sorts by `receivedDate`. */
231
+ function mergeInboxMessages(perMailbox) {
232
+ return perMailbox
233
+ .flatMap((entry) => entry.messages)
234
+ .sort((a, b) => new Date(b.receivedDate).getTime() - new Date(a.receivedDate).getTime());
235
+ }
236
+ /**
237
+ * Fans out one `listMessages()` call per accessible mailbox that has a folder of `type`, merges the
238
+ * results newest-first. A mailbox with no matching folder, or whose fetch fails, simply contributes
239
+ * nothing - one mailbox's absence/failure must not blank out every other mailbox's messages.
240
+ *
241
+ * **Pagination scope trim (deliberate, matching this file's own documented Tier 2/3 tradeoffs)**: there is
242
+ * no composite cursor across an arbitrary number of independently-paginated mailboxes in this pass - this
243
+ * always fetches exactly each mailbox's own first page (`MESSAGE_PAGE_SIZE`) and the caller never offers a
244
+ * "load more" for the result (see `InboxContent`'s own `hasMore` handling in aggregate mode) - a real
245
+ * composite-cursor "load more" per mailbox is a natural v2 if usage shows people scrolling past the first
246
+ * page in aggregate view often.
247
+ */
248
+ async function fetchAggregateMessages(mailboxFolders, type) {
249
+ const perMailbox = await Promise.all(mailboxFolders.map(async ({ mailbox, folders }) => {
250
+ const folder = folders.find((f) => f.type === type);
251
+ if (!folder) {
252
+ return { mailbox, messages: [] };
253
+ }
254
+ const messages = await listMessages(folder.uid, { limit: MESSAGE_PAGE_SIZE }).catch(() => []);
255
+ return { mailbox, messages };
256
+ }));
257
+ return mergeInboxMessages(perMailbox);
107
258
  }
108
259
  export default function InboxPage(props) {
109
260
  return (_jsx(MailShell, { ...props, children: _jsx(InboxContent, {}) }));
110
261
  }
111
262
  function InboxContent() {
112
- const { folderUid, mailboxUid, folders } = useMailShell();
263
+ const { folderUid, mailboxUid, mailboxes, mailboxFolders, aggregateFolderType } = useMailShell();
113
264
  const isMobile = useIsMobile();
265
+ const { requestUnlock } = useUnlockPrompt();
114
266
  const [viewMode, setViewMode] = useState("date");
115
267
  const [messages, setMessages] = useState([]);
116
268
  const [conversations, setConversations] = useState([]);
@@ -125,22 +277,130 @@ function InboxContent() {
125
277
  const [searchQuery, setSearchQuery] = useState("");
126
278
  const [snippets, setSnippets] = useState({});
127
279
  const [labels, setLabels] = useState([]);
128
- const isSearching = viewMode === "date" && searchQuery.length > 0;
280
+ // Tier 2's own reported window coverage for the current search - undefined outside a search, or
281
+ // before Tier 2 has resolved yet for this search pass.
282
+ const [coverage, setCoverage] = useState(undefined);
283
+ // Keyed by message uid - see decryptEncryptedRows(). Never cleared on folder/search switches (a
284
+ // decrypted row stays decrypted for the rest of the session; re-decrypting on every navigation would
285
+ // waste work for no benefit), only ever added to.
286
+ const [decryptedRows, setDecryptedRows] = useState({});
287
+ // Bumped after a successful on-demand unlock to re-run the search effect below - it's not a
288
+ // dependency the effect could otherwise react to (getUnlockedKeys() is a plain module-level read, not
289
+ // React state; see keySession.ts's own doc comment).
290
+ const [unlockRefresh, setUnlockRefresh] = useState(0);
291
+ // §_Progressive Results_: which of the current search's uids are still an unconfirmed Tier 1
292
+ // `metadataOnly` guess (rendered as a skeleton row - see the JSX below) - empty outside a search, and
293
+ // always empty again once every tier has reported for the current pass (each unresolved entry is by
294
+ // then either confirmed, real content, or pruned - see the search orchestration effect).
295
+ const [pendingUids, setPendingUids] = useState(new Set());
296
+ // Withholds a hard result count until every tier has reported for the current search pass (§_Progressive
297
+ // Results_: "Never show a hard count until every tier has reported... A settled count is the signal
298
+ // that ordering is final"). Reset on every fresh search; irrelevant outside search mode.
299
+ const [tier1Done, setTier1Done] = useState(false);
300
+ const [tier2Done, setTier2Done] = useState(false);
301
+ const [tier3Done, setTier3Done] = useState(false);
302
+ // Toggled by the "Search all mail" action next to the results count - removes Tier 3's own default
303
+ // bound (tightened to Tier 2's coverage window otherwise - see tightenBeforeToCoverage()) for one
304
+ // re-run. Reset to false whenever the query itself changes (see the search effect's own dependency).
305
+ const [searchAllMail, setSearchAllMail] = useState(false);
306
+ // Search stays real-folder-only - Tier 1/2/3 are all deeply mailbox/folder-scoped, and extending them
307
+ // to span an arbitrary number of mailboxes is out of scope for this pass (see the aggregate-fetch
308
+ // branch below, which the search effect never reaches while `folderUid` is unset).
309
+ const isSearching = viewMode === "date" && searchQuery.length > 0 && !aggregateFolderType;
129
310
  const pageRef = useRef(0);
130
- const cursorRef = useRef(undefined);
131
311
  const scrollContainerRef = useRef(null);
132
312
  const sentinelRef = useRef(null);
313
+ // The mailbox unlock/decrypt call sites below treat as "the" mailbox when there's no single selected
314
+ // one (aggregate mode) - mirrors `MailShell`'s own identical `defaultMailboxUid` fallback. An
315
+ // aggregate-view row from a *different*, not-yet-unlocked mailbox stays locked until that mailbox's
316
+ // own folder view is opened directly - an accepted limitation, not a bug (see `MailShell`'s own doc
317
+ // comment on the same tradeoff for its `LocalIndexLifecycle`/`KeyEnrollmentGate` wiring).
318
+ const activeMailboxUid = mailboxUid ?? mailboxes.find((mb) => mb.ownerUserUid)?.uid ?? mailboxes[0]?.uid;
319
+ const mailboxKeys = mailboxes.find((mb) => mb.uid === activeMailboxUid)?.keys ?? [];
320
+ // Reset to a fresh Map at the start of every new search pass (see the search effect below) - see
321
+ // resolveHitsToMessages()'s own doc comment on why this needs to persist *within* one pass but not
322
+ // across passes (a stale `null` for a uid that's since become resolvable elsewhere must not stick).
323
+ const resolvedMessageCacheRef = useRef(new Map());
324
+ // Session-scoped, never explicitly cleared - see Tier3Cache's own doc comment above.
325
+ const tier3CacheRef = useRef(new Map());
326
+ // The latest composite cursor this search pass has reached - read by loadMore(), written at the end
327
+ // of both the fresh-search orchestration and loadMore() itself. Not React state: it never drives a
328
+ // render on its own, only what loadMore() does with it later.
329
+ const compositeCursorRef = useRef(undefined);
330
+ // Guards every async stage of the search orchestration below against a stale, still-in-flight pass
331
+ // clobbering state for a newer one that started after it (the query changed again, or the folder
332
+ // did) - the same `loadSeq`-style monotonic-id pattern already used elsewhere in this codebase (e.g.
333
+ // `settings/privacy/index.tsx`'s `ExportSection`), generalized here across three independently-timed
334
+ // async stages instead of one.
335
+ const searchRunIdRef = useRef(0);
336
+ // `messages` themselves aren't a dependency here on purpose - a message uid, once decrypted, is
337
+ // never re-decrypted just because the list re-renders with the same rows (e.g. a folder-unrelated
338
+ // state update elsewhere). New rows (a fresh page load, load-more, or a completed search) each
339
+ // re-trigger this the normal way, by changing `messages` itself.
340
+ //
341
+ // Scoped to `activeMailboxUid`'s own rows only - in aggregate mode `messages` can span several
342
+ // mailboxes, but only one mailbox's keys are ever being unlocked/tracked here (see `activeMailboxUid`'s
343
+ // own doc comment above); an encrypted row from any other mailbox simply isn't a candidate for this
344
+ // auto-decrypt or the manual unlock banner below.
345
+ const undecryptedEncryptedUids = messages
346
+ .filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && !decryptedRows[m.uid] && m.mailboxUid === activeMailboxUid)
347
+ .map((m) => m.uid);
348
+ // Once unlocked, silently decrypt this page's own encrypted rows to show their real subject/preview -
349
+ // no prompt needed here, the same way searchEncryptedCandidates() already auto-includes decrypted
350
+ // matches once unlocked without asking again. Only the *first* unlock (or a fresh page of messages
351
+ // arriving) needs this; `handleUnlockList()` below covers the not-yet-unlocked case explicitly.
352
+ useEffect(() => {
353
+ if (undecryptedEncryptedUids.length === 0 || !activeMailboxUid) {
354
+ return;
355
+ }
356
+ const unlocked = getUnlockedKeys(activeMailboxUid);
357
+ if (!unlocked) {
358
+ return;
359
+ }
360
+ let cancelled = false;
361
+ decryptEncryptedRows(messages.filter((m) => undecryptedEncryptedUids.includes(m.uid)), unlocked).then((decrypted) => {
362
+ if (!cancelled && Object.keys(decrypted).length > 0) {
363
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
364
+ }
365
+ });
366
+ return () => {
367
+ cancelled = true;
368
+ };
369
+ // eslint-disable-next-line react-hooks/exhaustive-deps
370
+ }, [messages, unlockRefresh]);
371
+ async function handleUnlockList() {
372
+ try {
373
+ const unlocked = await requestUnlock(activeMailboxUid, mailboxKeys);
374
+ const decrypted = await decryptEncryptedRows(messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && m.mailboxUid === activeMailboxUid), unlocked);
375
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
376
+ }
377
+ catch {
378
+ // User dismissed the unlock dialog - rows stay exactly as they were.
379
+ }
380
+ }
381
+ async function handleUnlockSearch() {
382
+ try {
383
+ await requestUnlock(activeMailboxUid, mailboxKeys);
384
+ setUnlockRefresh((n) => n + 1);
385
+ }
386
+ catch {
387
+ // User dismissed the unlock dialog - the search results stay exactly as they were.
388
+ }
389
+ }
133
390
  // Labels are mailbox-wide, not folder-scoped - fetched once per mailbox rather than per message, and
134
391
  // handed to every `MessageDetailPane` instance below. A failure here just means the Labels control
135
392
  // stays hidden (an empty `labels` array) rather than blocking the rest of the inbox - it's a small
136
- // enhancement, not critical path the way the message list itself is. No `mailboxUid` guard needed -
137
- // `MailShell` never renders this component at all until `mailboxUid` has resolved (same invariant
138
- // `searchMessages(mailboxUid!, ...)` below already relies on).
393
+ // enhancement, not critical path the way the message list itself is. Keyed on `activeMailboxUid`, which
394
+ // `MailShell` guarantees resolves (it never renders this component without at least one mailbox) even
395
+ // in aggregate mode, where there's no single selected `mailboxUid`.
139
396
  useEffect(() => {
140
- listLabels(mailboxUid, { limit: 200 })
397
+ if (!activeMailboxUid) {
398
+ return;
399
+ }
400
+ listLabels(activeMailboxUid, { limit: 200 })
141
401
  .then(setLabels)
142
402
  .catch(() => setLabels([]));
143
- }, [mailboxUid]);
403
+ }, [activeMailboxUid]);
144
404
  // Debounce the raw input into the query actually searched, so every keystroke doesn't fire a request.
145
405
  useEffect(() => {
146
406
  const handle = setTimeout(() => setSearchQuery(searchInput.trim()), SEARCH_DEBOUNCE_MS);
@@ -154,20 +414,42 @@ function InboxContent() {
154
414
  setSelectedConversationId(null);
155
415
  setClassificationFilter("all");
156
416
  pageRef.current = 0;
157
- cursorRef.current = undefined;
417
+ compositeCursorRef.current = undefined;
158
418
  setHasMore(false);
159
419
  if (viewMode === "conversation") {
160
- // `mailboxUid` is always set by this point — `MailShell` only ever resolves `folderUid`
161
- // (this component's own guard just below, gating everything before this effect can even
162
- // run with `viewMode === "conversation"`) after `mailboxUid` is already known.
420
+ // Conversations stay single-mailbox (not aggregated across mailboxes in this pass) - in
421
+ // aggregate mode this falls back to `activeMailboxUid`, the same mailbox unlock/labels use.
422
+ if (!activeMailboxUid) {
423
+ return;
424
+ }
163
425
  setLoading(true);
164
426
  setError(null);
165
- listConversations(mailboxUid)
427
+ listConversations(activeMailboxUid)
166
428
  .then(setConversations)
167
429
  .catch((err) => setError(err instanceof ApiRequestError ? err.message : "Could not load conversations."))
168
430
  .finally(() => setLoading(false));
169
431
  return;
170
432
  }
433
+ if (aggregateFolderType) {
434
+ setLoading(true);
435
+ setError(null);
436
+ let cancelled = false;
437
+ // hasMore stays false (set above) - see fetchAggregateMessages()'s own pagination scope trim.
438
+ fetchAggregateMessages(mailboxFolders, aggregateFolderType)
439
+ .then((results) => {
440
+ if (!cancelled) {
441
+ setMessages(results);
442
+ }
443
+ })
444
+ .finally(() => {
445
+ if (!cancelled) {
446
+ setLoading(false);
447
+ }
448
+ });
449
+ return () => {
450
+ cancelled = true;
451
+ };
452
+ }
171
453
  if (!folderUid) {
172
454
  setMessages([]);
173
455
  setLoading(false);
@@ -176,15 +458,88 @@ function InboxContent() {
176
458
  setLoading(true);
177
459
  setError(null);
178
460
  if (isSearching) {
179
- searchMessages(mailboxUid, searchQuery)
180
- .then(({ messages: results, nextCursor, snippets: newSnippets }) => {
181
- setMessages(results);
182
- setSnippets(newSnippets);
183
- setHasMore(!!nextCursor);
184
- cursorRef.current = nextCursor;
185
- })
186
- .catch((err) => setError(err instanceof ApiRequestError ? err.message : "Search failed."))
187
- .finally(() => setLoading(false));
461
+ setCoverage(undefined);
462
+ setPendingUids(new Set());
463
+ setTier1Done(false);
464
+ setTier2Done(false);
465
+ setTier3Done(false);
466
+ resolvedMessageCacheRef.current = new Map();
467
+ searchRunIdRef.current += 1;
468
+ const myRunId = searchRunIdRef.current;
469
+ const parsed = parseSearchQuery(searchQuery);
470
+ const unlocked = getUnlockedKeys(mailboxUid);
471
+ const fingerprint = queryFingerprint(parsed);
472
+ // Recomputes and re-renders the merged list from whatever tiers have reported so far -
473
+ // called once after Tier 1+2 (interim: unconfirmed Tier 1 metadataOnly hits render as
474
+ // skeletons) and again after Tier 3 (final: anything still unconfirmed is pruned instead -
475
+ // §_Progressive Results_' "Skeletons resolve or disappear"). Bails out via `myRunId` if a
476
+ // newer search pass has since started.
477
+ async function reveal(tier1Hits, tier2Hits, tier3Hits, final) {
478
+ const capped = capSkeletons(tier1Hits);
479
+ const confirmed = new Set([...tier2Hits, ...tier3Hits].map((r) => r.entityUid));
480
+ const effectiveTier1 = final ? capped.filter((hit) => !hit.metadataOnly || confirmed.has(hit.entityUid)) : capped;
481
+ const merged = mergeSearchResults(effectiveTier1, tier2Hits, tier3Hits);
482
+ const { messages: resolved, snippets: resolvedSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
483
+ if (searchRunIdRef.current !== myRunId) {
484
+ return;
485
+ }
486
+ setMessages(resolved);
487
+ setSnippets(resolvedSnippets);
488
+ if (final) {
489
+ setPendingUids(new Set());
490
+ }
491
+ else {
492
+ const pending = new Set();
493
+ for (const hit of capped) {
494
+ if (hit.metadataOnly && !confirmed.has(hit.entityUid)) {
495
+ pending.add(hit.entityUid);
496
+ }
497
+ }
498
+ setPendingUids(pending);
499
+ }
500
+ }
501
+ void (async () => {
502
+ try {
503
+ const [tier1Page, tier2Page] = await Promise.all([
504
+ searchMailbox(parsed.text, tier1SearchParams(parsed, undefined)),
505
+ searchLocalIndex(mailboxUid, parsed, unlocked, MESSAGE_PAGE_SIZE, 0),
506
+ ]);
507
+ if (searchRunIdRef.current !== myRunId) {
508
+ return;
509
+ }
510
+ setTier1Done(true);
511
+ setTier2Done(true);
512
+ setCoverage(tier2Page.coverage);
513
+ setLoading(false);
514
+ await reveal(tier1Page.results, tier2Page.results, [], false);
515
+ const tightened = tightenBeforeToCoverage(parsed, tier2Page.coverage, searchAllMail);
516
+ const cacheKey = tier3CacheKey(mailboxUid, fingerprint, searchAllMail, !!unlocked);
517
+ let tier3Full = tier3CacheRef.current.get(cacheKey);
518
+ if (!tier3Full) {
519
+ tier3Full = await searchEncryptedCandidates(tightened, unlocked, TIER3_CANDIDATE_LIMIT);
520
+ if (searchRunIdRef.current !== myRunId) {
521
+ return;
522
+ }
523
+ tier3CacheRef.current.set(cacheKey, tier3Full);
524
+ }
525
+ const tier3Page = tier3Full.slice(0, MESSAGE_PAGE_SIZE);
526
+ setTier3Done(true);
527
+ compositeCursorRef.current = {
528
+ tier1Cursor: tier1Page.nextCursor,
529
+ tier2Offset: tier2Page.results.length,
530
+ tier3Offset: tier3Page.length,
531
+ fingerprint,
532
+ };
533
+ setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || tier3Page.length < tier3Full.length);
534
+ await reveal(tier1Page.results, tier2Page.results, tier3Page, true);
535
+ }
536
+ catch (err) {
537
+ if (searchRunIdRef.current === myRunId) {
538
+ setError(err instanceof ApiRequestError ? err.message : "Search failed.");
539
+ setLoading(false);
540
+ }
541
+ }
542
+ })();
188
543
  return;
189
544
  }
190
545
  listMessages(folderUid, { limit: MESSAGE_PAGE_SIZE })
@@ -194,7 +549,16 @@ function InboxContent() {
194
549
  })
195
550
  .catch((err) => setError(err instanceof ApiRequestError ? err.message : "Could not load messages."))
196
551
  .finally(() => setLoading(false));
197
- }, [viewMode, folderUid, mailboxUid, isSearching, searchQuery]);
552
+ // `unlockRefresh`/`searchAllMail` are dependencies solely so `handleUnlockSearch()`/"Search all
553
+ // mail" can force this effect to re-run the search above - Tier 3 (encrypted) results silently
554
+ // contribute nothing without unlocked keys, so this is what actually makes them appear once the
555
+ // user unlocks, and what makes "Search all mail" actually remove Tier 3's coverage bound. Neither
556
+ // has any effect on the non-search branch below; re-running it with identical inputs just
557
+ // re-fetches the same page.
558
+ }, [viewMode, folderUid, mailboxUid, isSearching, searchQuery, unlockRefresh, searchAllMail, aggregateFolderType, mailboxFolders, activeMailboxUid]);
559
+ function handleSearchAllMail() {
560
+ setSearchAllMail(true);
561
+ }
198
562
  const loadMore = useCallback(async () => {
199
563
  if (loadingMore || !hasMore || loading || viewMode !== "date" || !folderUid) {
200
564
  return;
@@ -202,11 +566,36 @@ function InboxContent() {
202
566
  setLoadingMore(true);
203
567
  try {
204
568
  if (isSearching) {
205
- const { messages: more, nextCursor, snippets: moreSnippets } = await searchMessages(mailboxUid, searchQuery, cursorRef.current);
569
+ const parsed = parseSearchQuery(searchQuery);
570
+ const unlocked = getUnlockedKeys(mailboxUid);
571
+ const fingerprint = queryFingerprint(parsed);
572
+ const cursor = decodeCursor(compositeCursorRef.current, fingerprint);
573
+ const [tier1Page, tier2Page] = await Promise.all([
574
+ searchMailbox(parsed.text, tier1SearchParams(parsed, cursor?.tier1Cursor)),
575
+ searchLocalIndex(mailboxUid, parsed, unlocked, MESSAGE_PAGE_SIZE, cursor?.tier2Offset ?? 0),
576
+ ]);
577
+ const cacheKey = tier3CacheKey(mailboxUid, fingerprint, searchAllMail, !!unlocked);
578
+ const tier3Full = tier3CacheRef.current.get(cacheKey) ?? [];
579
+ const tier3Offset = cursor?.tier3Offset ?? 0;
580
+ const tier3Page = tier3Full.slice(tier3Offset, tier3Offset + MESSAGE_PAGE_SIZE);
581
+ // Unlike the fresh-search pass above, a load-more page is resolved and appended in one
582
+ // shot rather than progressively revealed - rows already on screen shouldn't reorder or
583
+ // grow skeletons out from under a reader who has since scrolled past them. Any Tier 1
584
+ // metadataOnly hit this page that neither Tier 2 nor Tier 3 (both already awaited above)
585
+ // confirms simply keeps showing its existing placeholder text rather than a live skeleton
586
+ // - a deliberate, documented scope trim of progressive reveal to the first page only.
587
+ const merged = mergeSearchResults(capSkeletons(tier1Page.results), tier2Page.results, tier3Page);
588
+ const { messages: more, snippets: moreSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
206
589
  setMessages((prev) => [...prev, ...more]);
207
590
  setSnippets((prev) => ({ ...prev, ...moreSnippets }));
208
- setHasMore(!!nextCursor);
209
- cursorRef.current = nextCursor;
591
+ const nextTier3Offset = tier3Offset + tier3Page.length;
592
+ compositeCursorRef.current = {
593
+ tier1Cursor: tier1Page.nextCursor,
594
+ tier2Offset: (cursor?.tier2Offset ?? 0) + tier2Page.results.length,
595
+ tier3Offset: nextTier3Offset,
596
+ fingerprint,
597
+ };
598
+ setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || nextTier3Offset < tier3Full.length);
210
599
  }
211
600
  else {
212
601
  const nextPage = pageRef.current + 1;
@@ -222,7 +611,7 @@ function InboxContent() {
222
611
  finally {
223
612
  setLoadingMore(false);
224
613
  }
225
- }, [loadingMore, hasMore, loading, viewMode, folderUid, isSearching, searchQuery]);
614
+ }, [loadingMore, hasMore, loading, viewMode, folderUid, isSearching, searchQuery, searchAllMail, mailboxUid]);
226
615
  // Always calls the latest `loadMore` closure so the effect below doesn't need `loadMore` itself in its
227
616
  // dependency array (it changes on every keystroke/page load, which would otherwise mean nothing here).
228
617
  const loadMoreRef = useRef(loadMore);
@@ -251,16 +640,21 @@ function InboxContent() {
251
640
  // Search results can span every folder in the mailbox, not just the one selected in the sidebar - a
252
641
  // selected message's own folderUid is the only reliable source for its actual folder type once
253
642
  // searching (outside search, every message in `messages` already comes from `folderUid` itself, so
254
- // this falls back to the sidebar selection unchanged).
255
- const selectedFolderUid = isSearching ? (selected?.folderUid ?? folderUid) : folderUid;
643
+ // this falls back to the sidebar selection unchanged). Aggregate views span every *mailbox* too, so
644
+ // the folder list consulted is the selected message's own mailbox's, not the shell's ambient one.
645
+ const spansFolders = isSearching || !!aggregateFolderType;
646
+ const selectedFolderUid = spansFolders ? (selected?.folderUid ?? folderUid) : folderUid;
647
+ const selectedMailboxUid = spansFolders ? (selected?.mailboxUid ?? activeMailboxUid) : mailboxUid;
648
+ const folders = mailboxFolders.find((mf) => mf.mailbox.uid === selectedMailboxUid)?.folders ?? [];
256
649
  const isSentItems = folders.find((f) => f.uid === selectedFolderUid)?.type === "sent_items";
257
650
  const isOutbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "outbox";
258
651
  const isInbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "inbox";
259
652
  const draftsFolderUid = folders.find((f) => f.type === "drafts")?.uid;
260
653
  // Focused/Other is an Inbox-only concept (see `MessageDetailPane`'s own `isInbox` doc comment) — the
261
654
  // sub-tabs only ever render there, so a message with no `inferenceClassification` (the common case:
262
- // absent means Focused) or an explicit `"focused"` counts as Focused, everything else as Other.
263
- const visibleMessages = !isSearching && isInbox && classificationFilter !== "all"
655
+ // absent means Focused) or an explicit `"focused"` counts as Focused, everything else as Other. Not
656
+ // offered for an aggregate view (each mailbox classifies independently; merging that is out of scope).
657
+ const visibleMessages = !isSearching && !aggregateFolderType && isInbox && classificationFilter !== "all"
264
658
  ? messages.filter((m) => classificationFilter === "other"
265
659
  ? m.inferenceClassification === "other"
266
660
  : m.inferenceClassification !== "other")
@@ -285,7 +679,7 @@ function InboxContent() {
285
679
  }
286
680
  setSelectedConversationId(conversation.conversationId);
287
681
  }
288
- if (!folderUid) {
682
+ if (!folderUid && !aggregateFolderType) {
289
683
  // `MailShell` never renders this component at all until a mailbox is resolved (see its own
290
684
  // full-screen `MailboxProvisioning` takeover otherwise) — this is purely the brief gap before
291
685
  // that mailbox's own folder list has finished loading, not a "no mailbox" state. Distinct text
@@ -299,12 +693,16 @@ function InboxContent() {
299
693
  ].join(" "), children: "By date" }), _jsx("button", { type: "button", onClick: () => setViewMode("conversation"), className: [
300
694
  "flex-1 py-2 font-semibold",
301
695
  viewMode === "conversation" ? "text-primary-dark border-b-2 border-primary-dark" : "text-text-muted",
302
- ].join(" "), children: "By conversation" })] }), viewMode === "conversation" && (_jsx("p", { className: "p-3 text-xs text-text-muted border-b border-border", children: "Showing every conversation in this mailbox \u2014 the selected folder doesn't filter this view." })), viewMode === "date" && (_jsx("div", { className: "p-2 border-b border-border", children: _jsx("input", { type: "search", value: searchInput, onChange: (e) => setSearchInput(e.target.value), placeholder: "Search all mail\u2026", "aria-label": "Search all mail", className: "w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface" }) })), viewMode === "date" && isInbox && !isSearching && (_jsx("div", { className: "flex border-b border-border text-xs", children: ["all", "focused", "other"].map((value) => (_jsx("button", { type: "button", onClick: () => setClassificationFilter(value), className: [
696
+ ].join(" "), children: "By conversation" })] }), viewMode === "conversation" && (_jsx("p", { className: "p-3 text-xs text-text-muted border-b border-border", children: "Showing every conversation in this mailbox \u2014 the selected folder doesn't filter this view." })), viewMode === "date" && (_jsx("div", { className: "p-2 border-b border-border", children: _jsx("input", { type: "search", value: searchInput, onChange: (e) => setSearchInput(e.target.value), placeholder: aggregateFolderType ? "Open a mailbox's own folder to search" : "Search all mail…", "aria-label": "Search all mail", disabled: !!aggregateFolderType, className: "w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface disabled:opacity-55" }) })), viewMode === "date" && isInbox && !isSearching && !aggregateFolderType && (_jsx("div", { className: "flex border-b border-border text-xs", children: ["all", "focused", "other"].map((value) => (_jsx("button", { type: "button", onClick: () => setClassificationFilter(value), className: [
303
697
  "flex-1 py-1.5 font-semibold",
304
698
  classificationFilter === value
305
699
  ? "text-primary-dark border-b-2 border-primary-dark"
306
700
  : "text-text-muted",
307
- ].join(" "), children: value === "all" ? "All" : value === "focused" ? "Focused" : "Other" }, value))) })), error && (_jsx("div", { className: "p-4", children: _jsx(Alert, { children: error }) })), loading ? (_jsx("p", { className: "p-4 text-sm text-text-muted", children: "Loading\u2026" })) : viewMode === "conversation" ? (_jsx(ConversationList, { conversations: conversations, selectedId: selectedConversationId, onSelect: handleSelectConversation })) : visibleMessages.length === 0 ? (_jsx("p", { className: "p-4 text-sm text-text-muted", children: isSearching
701
+ ].join(" "), children: value === "all" ? "All" : value === "focused" ? "Focused" : "Other" }, value))) })), isSearching && (_jsxs("div", { className: "px-4 py-1.5 text-xs text-text-muted border-b border-border flex items-center justify-between gap-2", children: [_jsx("span", { children: tier1Done && tier2Done && tier3Done
702
+ ? `${visibleMessages.length} result${visibleMessages.length === 1 ? "" : "s"}`
703
+ : `${visibleMessages.length} of ??` }), tier2Done && !searchAllMail && (_jsx("button", { type: "button", onClick: handleSearchAllMail, className: "text-primary-dark hover:underline font-medium shrink-0", children: "Search all mail" }))] })), isSearching && coverage?.indexedFrom && (_jsxs("div", { className: "px-4 py-1.5 text-xs text-text-muted border-b border-border", children: ["Local search covers messages back to ", new Date(coverage.indexedFrom).toLocaleDateString(), coverage.building ? " (still building)" : "", searchAllMail
704
+ ? " - searching everything, not just recent mail."
705
+ : " - older encrypted mail is still searched, just slower."] })), isSearching && !getUnlockedKeys(mailboxUid) && (_jsx("div", { className: "px-4 py-2 border-b border-border bg-surface-alt", children: _jsxs("button", { type: "button", onClick: handleUnlockSearch, className: "inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline", children: [_jsx(HiOutlineLockClosed, { size: 12, "aria-hidden": "true" }), "Unlock to include encrypted messages in these results"] }) })), !isSearching && viewMode === "date" && undecryptedEncryptedUids.length > 0 && !getUnlockedKeys(activeMailboxUid) && (_jsx("div", { className: "px-4 py-2 border-b border-border bg-surface-alt", children: _jsxs("button", { type: "button", onClick: handleUnlockList, className: "inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline", children: [_jsx(HiOutlineLockClosed, { size: 12, "aria-hidden": "true" }), "Unlock to show ", undecryptedEncryptedUids.length === 1 ? "an encrypted message's" : "encrypted messages'", " subject"] }) })), error && (_jsx("div", { className: "p-4", children: _jsx(Alert, { children: error }) })), loading ? (_jsx("p", { className: "p-4 text-sm text-text-muted", children: "Loading\u2026" })) : viewMode === "conversation" ? (_jsx(ConversationList, { conversations: conversations, selectedId: selectedConversationId, onSelect: handleSelectConversation })) : visibleMessages.length === 0 ? (_jsx("p", { className: "p-4 text-sm text-text-muted", children: isSearching
308
706
  ? `No messages match "${searchQuery}".`
309
707
  : classificationFilter === "all"
310
708
  ? "No messages in this folder."
@@ -312,7 +710,11 @@ function InboxContent() {
312
710
  "w-full text-left px-4 py-3 border-b border-border",
313
711
  message.uid === selectedUid ? "bg-primary/10" : "hover:bg-surface-alt",
314
712
  message.flags.read ? "" : "font-semibold",
315
- ].join(" "), children: [_jsxs("div", { className: "flex items-center justify-between gap-2 text-sm", children: [_jsx("span", { className: "truncate", children: message.from.displayName || message.from.address }), _jsx("span", { className: "text-xs text-text-muted shrink-0", children: new Date(message.receivedDate).toLocaleDateString() })] }), _jsx("div", { className: "text-sm truncate", children: message.subject || "(no subject)" }), _jsx("div", { className: "text-xs text-text-muted truncate font-normal", children: snippets[message.uid] || message.bodyPreview })] }) }, message.uid))) }), hasMore && (_jsx("div", { ref: sentinelRef, className: "p-4 text-center text-xs text-text-muted", children: loadingMore ? "Loading more…" : "" }))] }))] }), _jsx("div", { className: "hidden md:flex flex-1 min-w-0", children: viewMode === "conversation" ? (_jsx(ConversationThreadPane, { conversation: selectedConversation, folders: folders, labels: labels })) : (_jsx(MessageDetailPane, { message: selected, attachments: attachments, isSentItems: isSentItems, onRecalled: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), isOutbox: isOutbox, isInbox: isInbox, onClassified: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), onReceiptHandled: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), draftsFolderUid: draftsFolderUid, onScheduledSendCanceled: (updated) => {
713
+ ].join(" "), children: [_jsxs("div", { className: "flex items-center justify-between gap-2 text-sm", children: [_jsx("span", { className: "truncate", children: message.from.displayName || message.from.address }), _jsx("span", { className: "text-xs text-text-muted shrink-0", children: new Date(message.receivedDate).toLocaleDateString() })] }), aggregateFolderType && (_jsx("div", { className: "text-xs text-text-muted truncate font-normal", children: mailboxes.find((mb) => mb.uid === message.mailboxUid)?.displayName })), isSearching && pendingUids.has(message.uid) ? (_jsxs("div", { className: "flex flex-col gap-1.5 py-0.5", children: [_jsx(Skeleton, { height: "h-3.5", className: "w-2/3 rounded-sm" }), _jsx(Skeleton, { height: "h-3", className: "w-full rounded-sm" })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "text-sm truncate", children: decryptedRows[message.uid]?.subject ||
714
+ (message.subject === ENCRYPTED_SUBJECT_PLACEHOLDER
715
+ ? "Encrypted message"
716
+ : message.subject) ||
717
+ "(no subject)" }), _jsx("div", { className: "text-xs text-text-muted truncate font-normal", children: snippets[message.uid] || decryptedRows[message.uid]?.preview || message.bodyPreview })] }))] }) }, message.uid))) }), hasMore && (_jsx("div", { ref: sentinelRef, className: "p-4 text-center text-xs text-text-muted", children: loadingMore ? "Loading more…" : "" })), aggregateFolderType && (_jsx("p", { className: "p-4 text-center text-xs text-text-muted", children: "Showing the most recent mail from each mailbox. Open a specific mailbox\u2019s folder to see older mail." }))] }))] }), _jsx("div", { className: "hidden md:flex flex-1 min-w-0", children: viewMode === "conversation" ? (_jsx(ConversationThreadPane, { conversation: selectedConversation, folders: mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? [], labels: labels })) : (_jsx(MessageDetailPane, { message: selected, attachments: attachments, isSentItems: isSentItems, onRecalled: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), isOutbox: isOutbox, isInbox: isInbox, onClassified: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), onReceiptHandled: (updated) => setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m))), draftsFolderUid: draftsFolderUid, onScheduledSendCanceled: (updated) => {
316
718
  // The message moved out of the currently-viewed Outbox folder (into Drafts)
317
719
  // — unlike a recall, which patches a message in place, this removes it from
318
720
  // the list entirely, matching what a real folder switch would show.