feat: cross-account "All accounts" views + full group/shared-account support

Add cross-account aggregate mail views and make group/shared (delegated)
accounts first-class in every aggregate view. (The unified mailbox, the "All
Mail" view, and "include group inboxes" already exist on main; this branch adds
the cross-account views and the shared-account correctness work.)

New views (admin-gated + per-user toggle, nested under Unified Mailbox):
- Cross-account "All accounts": All unread / All starred / All mail across every
  connected account, including shared/group folders. Each list labels the source
  folder of every message.

Source reference on aggregated emails (the core of the shared-account work):
- Replace the overloaded `accountId` with two explicit, always-set fields:
  `sourceClientAccountId` (the login the mail is reachable through) and
  `sourceAccountId` (the owning JMAP account). `accountId` stays display-only.
- Resolution is branch-free everywhere: pick the client by sourceClientAccountId,
  pass sourceAccountId as the JMAP accountId (no-op for personal), read the
  owner's mailbox list cached by JMAP id. No capability scan.

Shared/group-account correctness across all aggregate views:
- Route open (click + auto-fetch), thread/conversation open + reply-refresh,
  mark read, star, move, delete (account-scoped trash), archive (owner-routed
  createMailbox / fetchAccountMailboxes), and spam + undo via the source ref.
- Add accountId params to toggleStar / batchMarkAsRead / batchDeleteEmails /
  createMailbox where missing.
- Fix local unread/total counter math for shared folders via emailInMailbox()
  (matches namespaced shared ids and bare own ids).
- Keep the unified/cross virtual selection on background mailbox refresh (no
  jump back to inbox after deleting in All Drafts/Junk).

Junk UX:
- In "All Junk" the spam action becomes "not spam" in the viewer, context menu,
  and list hover icons; undo routes shared mail back to its own inbox.

Admin:
- Policy gates crossUnread/Starred/AllViewEnabled, each noting the matching
  per-user toggle (allMailViewEnabled clarified too).

i18n / docs / tests:
- locales (19): cross-view labels + descriptions and hover not_spam, translated
  in all shipped languages.
- FEATURES.md + README.md document the new views and group-account support.
- Tests for shared-account routing (single + batch + undoSpam), decoration, and
  unified-selection preservation.
This commit is contained in:
Stefan Hildebrandt
2026-06-23 19:16:22 +02:00
parent 3dd596ba50
commit a29c33b50a
41 changed files with 1491 additions and 226 deletions
+169
View File
@@ -0,0 +1,169 @@
import { describe, it, expect, vi } from 'vitest';
import type { Email, Mailbox } from '@/lib/jmap/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
import {
getCrossIncludedMailboxes,
buildCrossFilter,
getCrossUnreadTotal,
fetchCrossViewEmails,
resolveSourceFolderName,
type UnifiedAccountClient,
} from '@/lib/unified-mailbox';
const mb = (id: string, role: string | undefined, unread = 0, originalId?: string): Mailbox =>
({ id, name: id, role, unreadEmails: unread, totalEmails: 0, originalId } as unknown as Mailbox);
const makeAccount = (
over: Partial<UnifiedAccountClient> & { accountId: string },
clientImpl: Partial<IJMAPClient> = {},
): UnifiedAccountClient => ({
accountLabel: over.accountId,
mailboxes: [],
client: clientImpl as unknown as IJMAPClient,
clientAccountId: over.accountId,
jmapAccountId: over.accountId,
...over,
});
describe('getCrossIncludedMailboxes', () => {
it('excludes junk/sent/archive/trash/drafts, keeps inbox + custom folders', () => {
const account = makeAccount({
accountId: 'a',
mailboxes: [
mb('inbox', 'inbox'),
mb('projects', undefined),
mb('junk', 'junk'),
mb('sent', 'sent'),
mb('archive', 'archive'),
mb('trash', 'trash'),
mb('drafts', 'drafts'),
],
});
const ids = getCrossIncludedMailboxes(account).map((m) => m.id);
expect(ids).toEqual(['inbox', 'projects']);
});
});
describe('buildCrossFilter', () => {
it('all → single inMailbox for one folder', () => {
expect(buildCrossFilter('all', ['m1'])).toEqual({ inMailbox: 'm1' });
});
it('all → OR of inMailbox for multiple folders', () => {
expect(buildCrossFilter('all', ['m1', 'm2'])).toEqual({
operator: 'OR',
conditions: [{ inMailbox: 'm1' }, { inMailbox: 'm2' }],
});
});
it('unread → AND(membership, notKeyword $seen)', () => {
expect(buildCrossFilter('unread', ['m1', 'm2'])).toEqual({
operator: 'AND',
conditions: [
{ operator: 'OR', conditions: [{ inMailbox: 'm1' }, { inMailbox: 'm2' }] },
{ notKeyword: '$seen' },
],
});
});
it('starred → AND(membership, hasKeyword $flagged)', () => {
expect(buildCrossFilter('starred', ['m1'])).toEqual({
operator: 'AND',
conditions: [{ inMailbox: 'm1' }, { hasKeyword: '$flagged' }],
});
});
});
describe('getCrossUnreadTotal', () => {
it('sums unread across included folders of every account, ignoring excluded roles', () => {
const a = makeAccount({
accountId: 'a',
mailboxes: [mb('inbox', 'inbox', 3), mb('proj', undefined, 2), mb('junk', 'junk', 50)],
});
const b = makeAccount({
accountId: 'b',
mailboxes: [mb('inbox', 'inbox', 5), mb('sent', 'sent', 99)],
});
expect(getCrossUnreadTotal([a, b])).toBe(10);
});
});
describe('resolveSourceFolderName', () => {
const emailIn = (ids: string[]): Email =>
({ mailboxIds: Object.fromEntries(ids.map((id) => [id, true])) } as unknown as Email);
it('returns the name of the folder the email is in (personal account)', () => {
const boxes = [mb('inbox', 'inbox'), mb('proj', undefined)];
expect(resolveSourceFolderName(emailIn(['proj']), boxes)).toBe('proj');
});
it('matches shared mailboxes by originalId (email keyed by owner-side id)', () => {
// shared mailbox: namespaced store id, but email.mailboxIds uses originalId
const shared = { id: 'owner:inbox', role: 'inbox', unreadEmails: 0, totalEmails: 0, originalId: 'orig-inbox', name: 'Team Inbox' } as unknown as Mailbox;
expect(resolveSourceFolderName(emailIn(['orig-inbox']), [shared])).toBe('Team Inbox');
});
it('returns undefined when no known folder contains the email', () => {
expect(resolveSourceFolderName(emailIn(['unknown']), [mb('inbox', 'inbox')])).toBeUndefined();
});
});
describe('fetchCrossViewEmails', () => {
it('merges + date-sorts across accounts and stamps account info', async () => {
const clientA = {
advancedSearchEmails: vi.fn().mockResolvedValue({
emails: [{ id: 'a1', receivedAt: '2026-01-01T10:00:00Z' } as Email],
total: 1,
hasMore: false,
}),
};
const clientB = {
advancedSearchEmails: vi.fn().mockResolvedValue({
emails: [{ id: 'b1', receivedAt: '2026-01-02T10:00:00Z' } as Email],
total: 1,
hasMore: true,
}),
};
const a = makeAccount({ accountId: 'a', accountLabel: 'A', mailboxes: [mb('inbox', 'inbox')] }, clientA);
const b = makeAccount({ accountId: 'b', accountLabel: 'B', mailboxes: [mb('inbox', 'inbox')] }, clientB);
const result = await fetchCrossViewEmails([a, b], 'all', 50, 0);
expect(result.emails.map((e) => e.id)).toEqual(['b1', 'a1']); // newest first
expect(result.emails[0].accountId).toBe('b');
expect(result.emails[1].accountLabel).toBe('A');
expect(result.total).toBe(2);
expect(result.hasMore).toBe(true);
});
it('resolves shared folders via originalId + owner accountId', async () => {
const advancedSearchEmails = vi.fn().mockResolvedValue({ emails: [], total: 0, hasMore: false });
const shared = makeAccount(
{ accountId: 'owner-1', accountLabel: 'Shared', isShared: true, mailboxes: [mb('ns:inbox', 'inbox', 0, 'orig-inbox')] },
{ advancedSearchEmails },
);
await fetchCrossViewEmails([shared], 'unread', 50, 0);
const [filter, accountId] = advancedSearchEmails.mock.calls[0];
expect(accountId).toBe('owner-1');
// filter membership uses the originalId, not the namespaced id
expect(JSON.stringify(filter)).toContain('orig-inbox');
expect(JSON.stringify(filter)).not.toContain('ns:inbox');
});
it('collects per-account errors without failing the whole fan-out', async () => {
const ok = makeAccount(
{ accountId: 'ok', mailboxes: [mb('inbox', 'inbox')] },
{ advancedSearchEmails: vi.fn().mockResolvedValue({ emails: [{ id: 'x', receivedAt: '2026-01-01T00:00:00Z' } as Email], total: 1, hasMore: false }) },
);
const bad = makeAccount(
{ accountId: 'bad', mailboxes: [mb('inbox', 'inbox')] },
{ advancedSearchEmails: vi.fn().mockRejectedValue(new Error('boom')) },
);
const result = await fetchCrossViewEmails([ok, bad], 'all', 50, 0);
expect(result.emails.map((e) => e.id)).toEqual(['x']);
expect(result.errors.get('bad')).toBe('boom');
});
});
+4
View File
@@ -28,6 +28,8 @@ function makeAccount(
accountLabel: over.accountId,
mailboxes: [],
client: clientImpl as unknown as IJMAPClient,
clientAccountId: over.accountId,
jmapAccountId: over.accountId,
...over,
};
}
@@ -71,6 +73,8 @@ describe('fetchUnifiedEmails', () => {
const a2 = result.emails.find((e) => e.id === 'a2')!;
expect(a2.accountId).toBe('A');
expect(a2.accountLabel).toBe('Account A');
expect(a2.sourceClientAccountId).toBe('A');
expect(a2.sourceAccountId).toBe('A');
// getEmails called with (mailboxId, accountId=undefined for personal, limit, position)
expect(acc1.client.getEmails).toHaveBeenCalledWith('a-in', undefined, 20, 0);
});
+6
View File
@@ -60,6 +60,9 @@ export interface FeatureGates {
filesEnabled: boolean;
contactsEnabled: boolean;
allMailViewEnabled: boolean;
crossUnreadViewEnabled: boolean;
crossStarredViewEnabled: boolean;
crossAllViewEnabled: boolean;
}
export const DEFAULT_FEATURE_GATES: FeatureGates = {
@@ -81,6 +84,9 @@ export const DEFAULT_FEATURE_GATES: FeatureGates = {
filesEnabled: true,
contactsEnabled: true,
allMailViewEnabled: false,
crossUnreadViewEnabled: false,
crossStarredViewEnabled: false,
crossAllViewEnabled: false,
};
export interface ThemePolicy {
+4 -4
View File
@@ -121,7 +121,7 @@ export class DemoJMAPClient implements IJMAPClient {
async getMailboxes(_accountId?: string): Promise<Mailbox[]> { return [...this.data.mailboxes]; }
async getAllMailboxes(): Promise<Mailbox[]> { return [...this.data.mailboxes]; }
async createMailbox(name: string, parentId?: string): Promise<Mailbox> {
async createMailbox(name: string, parentId?: string, _accountId?: string): Promise<Mailbox> {
const mb: Mailbox = {
id: generateDemoId('mailbox'),
name,
@@ -222,7 +222,7 @@ export class DemoJMAPClient implements IJMAPClient {
this.recalcMailboxCounts();
}
async batchMarkAsRead(emailIds: string[], read: boolean = true): Promise<void> {
async batchMarkAsRead(emailIds: string[], read: boolean = true, _accountId?: string): Promise<void> {
for (const id of emailIds) {
const email = this.data.emails.find(e => e.id === id);
if (email) {
@@ -233,7 +233,7 @@ export class DemoJMAPClient implements IJMAPClient {
this.recalcMailboxCounts();
}
async toggleStar(emailId: string, starred: boolean): Promise<void> {
async toggleStar(emailId: string, starred: boolean, _accountId?: string): Promise<void> {
const email = this.data.emails.find(e => e.id === emailId);
if (!email) return;
if (starred) email.keywords.$flagged = true;
@@ -275,7 +275,7 @@ export class DemoJMAPClient implements IJMAPClient {
this.recalcMailboxCounts();
}
async batchDeleteEmails(emailIds: string[]): Promise<void> {
async batchDeleteEmails(emailIds: string[], _accountId?: string): Promise<void> {
const idSet = new Set(emailIds);
this.data.emails = this.data.emails.filter(e => !idSet.has(e.id));
this.recalcMailboxCounts();
+4 -4
View File
@@ -73,7 +73,7 @@ export interface IJMAPClient {
// ── Mailboxes ─────────────────────────────────────────────────
getMailboxes(accountId?: string): Promise<Mailbox[]>;
getAllMailboxes(): Promise<Mailbox[]>;
createMailbox(name: string, parentId?: string): Promise<Mailbox>;
createMailbox(name: string, parentId?: string, accountId?: string): Promise<Mailbox>;
updateMailbox(mailboxId: string, changes: { name?: string; parentId?: string | null; role?: string | null; sortOrder?: number }): Promise<void>;
deleteMailbox(mailboxId: string): Promise<void>;
@@ -92,14 +92,14 @@ export interface IJMAPClient {
// ── Email mutations ───────────────────────────────────────────
markAsRead(emailId: string, read?: boolean, accountId?: string): Promise<void>;
batchMarkAsRead(emailIds: string[], read?: boolean): Promise<void>;
toggleStar(emailId: string, starred: boolean): Promise<void>;
batchMarkAsRead(emailIds: string[], read?: boolean, accountId?: string): Promise<void>;
toggleStar(emailId: string, starred: boolean, accountId?: string): Promise<void>;
updateEmailKeywords(emailId: string, keywords: Record<string, boolean>): Promise<void>;
setKeyword(emailId: string, keyword: string): Promise<void>;
migrateKeyword(oldKeyword: string, newKeyword: string): Promise<number>;
deleteEmail(emailId: string, accountId?: string): Promise<void>;
moveToTrash(emailId: string, trashMailboxId: string, accountId?: string, markAsRead?: boolean): Promise<void>;
batchDeleteEmails(emailIds: string[]): Promise<void>;
batchDeleteEmails(emailIds: string[], accountId?: string): Promise<void>;
batchMoveEmails(emailIds: string[], toMailboxId: string, accountId?: string, markAsRead?: boolean): Promise<void>;
batchArchiveEmails(
emails: Array<{ id: string; receivedAt: string }>,
+8 -8
View File
@@ -1273,19 +1273,19 @@ export class JMAPClient implements IJMAPClient {
]);
}
async batchMarkAsRead(emailIds: string[], read: boolean = true): Promise<void> {
async batchMarkAsRead(emailIds: string[], read: boolean = true, accountId?: string): Promise<void> {
if (emailIds.length === 0) return;
const updates = Object.fromEntries(emailIds.map(id => [id, { "keywords/$seen": read }]));
await this.request([
["Email/set", { accountId: this.accountId, update: updates }, "0"],
["Email/set", { accountId: accountId || this.accountId, update: updates }, "0"],
]);
}
async toggleStar(emailId: string, starred: boolean): Promise<void> {
async toggleStar(emailId: string, starred: boolean, accountId?: string): Promise<void> {
await this.request([
["Email/set", {
accountId: this.accountId,
accountId: accountId || this.accountId,
update: {
[emailId]: {
"keywords/$flagged": starred,
@@ -1391,12 +1391,12 @@ export class JMAPClient implements IJMAPClient {
]);
}
async batchDeleteEmails(emailIds: string[]): Promise<void> {
async batchDeleteEmails(emailIds: string[], accountId?: string): Promise<void> {
if (emailIds.length === 0) return;
await this.request([
["Email/set", {
accountId: this.accountId,
accountId: accountId || this.accountId,
destroy: emailIds,
}, "0"],
]);
@@ -1709,7 +1709,7 @@ export class JMAPClient implements IJMAPClient {
]);
}
async createMailbox(name: string, parentId?: string): Promise<Mailbox> {
async createMailbox(name: string, parentId?: string, accountId?: string): Promise<Mailbox> {
const createId = `new-${Date.now()}`;
const createData: Record<string, unknown> = { name };
if (parentId) {
@@ -1718,7 +1718,7 @@ export class JMAPClient implements IJMAPClient {
const response = await this.request([
["Mailbox/set", {
accountId: this.accountId,
accountId: accountId || this.accountId,
create: { [createId]: createData },
}, "0"],
]);
+54 -1
View File
@@ -58,9 +58,27 @@ export interface Email {
// S/MIME support
blobId?: string;
bodyStructure?: EmailBodyPart;
// Unified mailbox support - set when displaying emails from multiple accounts
// Unified mailbox support - set when displaying emails from multiple accounts.
// `accountId` is a DISPLAY-only reference (avatar color / label / badge) and may
// hold either an AccountEntry.id (personal) or the JMAP owner id (shared). For
// resolving the client + JMAP routing use the two dedicated fields below, which
// are always set on aggregated emails and unambiguous.
accountId?: string;
accountLabel?: string;
// AccountEntry.id of the logged-in client through which this email is reachable.
// Always a real login key → `useAuthStore.getClientForAccount(...)` resolves it.
// For personal sources this equals the account itself; for shared/group sources
// it is the delegating login (the shared account has no own login).
sourceClientAccountId?: string;
// JMAP account id of the email's owning account (personal: the client's primary;
// shared/group: the owner account). Always safe to pass as the JMAP `accountId`
// argument — equal to the client's primary for personal sources, so it is a no-op
// there, and triggers owner-scoped routing + mailbox-id namespacing for shared.
sourceAccountId?: string;
// Name of the email's originating folder, stamped for the aggregate "All …"
// views (All Mail, unified, cross-account) so the list can show where each
// message lives. Transient/client-only, not part of the JMAP object.
sourceFolder?: string;
// Client-only scheduled-send metadata, populated from EmailSubmission/query.
scheduledSendAt?: string;
emailSubmissionId?: string;
@@ -879,3 +897,38 @@ export function isUnifiedMailboxId(id: string): boolean {
* included is a per-user setting (see `allMailFolderIds`).
*/
export const ALL_MAIL_MAILBOX_ID = '__all_mail__';
/**
* Cross-account "All …" views shown in the unified ("All accounts") section.
* Each merges messages across EVERY account (including shared/group folders),
* spanning all folders except junk/spam, sent, archive, trash and drafts, in
* one date-sorted list. Distinct from the per-role unified ids (one role across
* accounts) and from ALL_MAIL_MAILBOX_ID (all folders of a single account).
*/
export const CROSS_UNREAD = '__cross_unread__';
export const CROSS_STARRED = '__cross_starred__';
export const CROSS_ALL = '__cross_all__';
export type CrossView = 'unread' | 'starred' | 'all';
export const CROSS_VIEW_IDS: Record<CrossView, string> = {
unread: CROSS_UNREAD,
starred: CROSS_STARRED,
all: CROSS_ALL,
};
export const CROSS_VIEW_BY_ID: Record<string, CrossView> = Object.fromEntries(
Object.entries(CROSS_VIEW_IDS).map(([view, id]) => [id, view as CrossView])
) as Record<string, CrossView>;
export function isCrossViewId(id: string): boolean {
return id in CROSS_VIEW_BY_ID;
}
/**
* Mailbox roles excluded from the cross-account views. Everything else (inbox
* and custom/no-role folders) is included.
*/
export const CROSS_EXCLUDED_ROLES: ReadonlySet<string> = new Set([
'junk', 'sent', 'archive', 'trash', 'drafts',
]);
+170 -1
View File
@@ -1,11 +1,22 @@
import type { Email, Mailbox, UnifiedMailboxRole } from '@/lib/jmap/types';
import type { Email, Mailbox, UnifiedMailboxRole, CrossView } from '@/lib/jmap/types';
import { CROSS_EXCLUDED_ROLES } from '@/lib/jmap/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
export interface UnifiedAccountClient {
// Display reference (avatar color / label). For personal entries this is the
// AccountEntry.id; for shared entries it is the JMAP owner id (see Email.accountId).
accountId: string;
accountLabel: string;
client: IJMAPClient;
mailboxes: Mailbox[];
// AccountEntry.id of the logged-in client this entry uses (`getClientForAccount`
// key). Stamped onto each email as `sourceClientAccountId` so single-email and
// batch actions can resolve the reaching client without scanning capabilities.
clientAccountId: string;
// JMAP account id of the data this entry reads (personal: the client's primary;
// shared: the owner id). Stamped onto each email as `sourceAccountId` and passed
// as the JMAP `accountId` for owner-scoped routing + mailbox-id namespacing.
jmapAccountId: string;
// When true, this entry represents a group/shared account owned by
// `accountId` but accessed through someone else's `client`. JMAP requests
// must use the mailbox's `originalId` and explicitly target this accountId
@@ -30,6 +41,19 @@ const ALL_UNIFIED_ROLES: UnifiedMailboxRole[] = [
'inbox', 'sent', 'drafts', 'trash', 'archive', 'junk',
];
/**
* Resolves the display name of the folder an email lives in, for the aggregate
* "All …" views. Matches the email's mailbox membership against the account's
* mailbox list (originalId for shared/namespaced mailboxes). Returns the first
* match, or undefined if none of the account's known folders contain it.
*/
export function resolveSourceFolderName(email: Email, mailboxes: Mailbox[]): string | undefined {
for (const m of mailboxes) {
if (email.mailboxIds?.[m.originalId ?? m.id]) return m.name;
}
return undefined;
}
/**
* Finds the first mailbox matching the given role.
*/
@@ -99,6 +123,9 @@ export async function fetchUnifiedEmails(
for (const email of result.emails) {
email.accountId = account.accountId;
email.accountLabel = account.accountLabel;
email.sourceClientAccountId = account.clientAccountId;
email.sourceAccountId = account.jmapAccountId;
email.sourceFolder = resolveSourceFolderName(email, account.mailboxes);
}
mergedEmails = mergedEmails.concat(result.emails);
@@ -223,6 +250,9 @@ async function fanOutUnifiedQuery(
for (const email of result.emails) {
email.accountId = account.accountId;
email.accountLabel = account.accountLabel;
email.sourceClientAccountId = account.clientAccountId;
email.sourceAccountId = account.jmapAccountId;
email.sourceFolder = resolveSourceFolderName(email, account.mailboxes);
}
mergedEmails = mergedEmails.concat(result.emails);
totalSum += result.total;
@@ -269,6 +299,145 @@ export function fetchUnifiedMailboxCounts(
return counts;
}
// ─── Cross-account views (unread / starred / all) ─────────────────────────────
//
// These merge messages across EVERY account (including shared) and across all
// folders except the CROSS_EXCLUDED_ROLES (junk, sent, archive, trash, drafts),
// i.e. inbox + custom folders, into one date-sorted list. Unlike the per-role
// unified fan-out above, the query spans many mailboxes per account, so the
// filter is built from each account's included-mailbox ids.
/**
* Mailboxes of an account included in the cross-account views: everything whose
* role is not excluded (inbox + custom/no-role folders).
*/
export function getCrossIncludedMailboxes(account: UnifiedAccountClient): Mailbox[] {
return account.mailboxes.filter((m) => !CROSS_EXCLUDED_ROLES.has(m.role ?? ''));
}
/**
* Builds the JMAP Email/query filter for a cross-account view over the given
* JMAP-side mailbox ids. `all` is just the mailbox membership; `unread` and
* `starred` AND a keyword condition onto it.
*/
export function buildCrossFilter(
view: CrossView,
jmapMailboxIds: string[],
): Record<string, unknown> {
const inAny: Record<string, unknown> = jmapMailboxIds.length === 1
? { inMailbox: jmapMailboxIds[0] }
: { operator: 'OR', conditions: jmapMailboxIds.map((id) => ({ inMailbox: id })) };
if (view === 'all') return inAny;
const keyword = view === 'unread' ? { notKeyword: '$seen' } : { hasKeyword: '$flagged' };
return { operator: 'AND', conditions: [inAny, keyword] };
}
/**
* Total unread count across every account's included cross-view mailboxes. Used
* for the unread badge on the "All unread" and "All mail" entries. Mirrors the
* unified count behaviour (sum of per-mailbox unread metadata, no extra query).
*/
export function getCrossUnreadTotal(accounts: UnifiedAccountClient[]): number {
let unread = 0;
for (const account of accounts) {
for (const m of getCrossIncludedMailboxes(account)) unread += m.unreadEmails;
}
return unread;
}
async function fanOutCrossQuery(
accounts: UnifiedAccountClient[],
run: (
account: UnifiedAccountClient,
jmapAccountId: string | undefined,
includedJmapIds: string[],
) => Promise<{ emails: Email[]; total: number; hasMore: boolean }>,
): Promise<UnifiedFetchResult> {
const errors = new Map<string, string>();
type AccountResult = {
account: UnifiedAccountClient;
result: { emails: Email[]; total: number; hasMore: boolean };
} | null;
const promises = accounts.map(async (account): Promise<AccountResult> => {
const included = getCrossIncludedMailboxes(account);
if (included.length === 0) return null;
const jmapAccountId = account.isShared ? account.accountId : undefined;
const includedJmapIds = included.map((m) => account.isShared ? (m.originalId ?? m.id) : m.id);
try {
const result = await run(account, jmapAccountId, includedJmapIds);
return { account, result };
} catch (err) {
errors.set(account.accountId, err instanceof Error ? err.message : String(err));
return null;
}
});
const results = await Promise.allSettled(promises);
let mergedEmails: Email[] = [];
let totalSum = 0;
let anyHasMore = false;
for (const outcome of results) {
if (outcome.status !== 'fulfilled' || outcome.value === null) continue;
const { account, result } = outcome.value;
for (const email of result.emails) {
email.accountId = account.accountId;
email.accountLabel = account.accountLabel;
email.sourceClientAccountId = account.clientAccountId;
email.sourceAccountId = account.jmapAccountId;
email.sourceFolder = resolveSourceFolderName(email, account.mailboxes);
}
mergedEmails = mergedEmails.concat(result.emails);
totalSum += result.total;
if (result.hasMore) anyHasMore = true;
}
mergedEmails.sort((a, b) => {
const dateA = new Date(a.receivedAt).getTime();
const dateB = new Date(b.receivedAt).getTime();
return dateB - dateA;
});
return { emails: mergedEmails, total: totalSum, hasMore: anyHasMore, errors };
}
/**
* Fetches a cross-account view (browse), merging and date-sorting across all
* accounts. Per-account failures are collected in the errors map.
*/
export async function fetchCrossViewEmails(
accounts: UnifiedAccountClient[],
view: CrossView,
limit: number,
position: number,
): Promise<UnifiedFetchResult> {
return fanOutCrossQuery(accounts, (account, jmapAccountId, ids) =>
account.client.advancedSearchEmails(buildCrossFilter(view, ids), jmapAccountId, limit, position));
}
/**
* Text search within a cross-account view: the view filter AND a free-text
* condition, fanned out across accounts.
*/
export async function searchCrossViewEmails(
accounts: UnifiedAccountClient[],
view: CrossView,
query: string,
limit: number,
position: number,
): Promise<UnifiedFetchResult> {
return fanOutCrossQuery(accounts, (account, jmapAccountId, ids) =>
account.client.advancedSearchEmails(
{ operator: 'AND', conditions: [buildCrossFilter(view, ids), { text: query }] },
jmapAccountId,
limit,
position,
));
}
/**
* Returns the list of unified roles that exist in at least one account's
* mailboxes.