Merge pull request #509 from hildebrandttk/feat/unified-mailbox-account-scope

Feat/unified mailbox account scope

Rework the sidebar "All accounts" into an account-bounded "Unified Mailbox"
by default, with cross-account merging as an opt-in (admin-gated) sub-option.
The standalone per-account "All Mail" virtual folder is folded into the unified
All mail / Unread / Starred entries.

Conflict resolution notes:
- stores/settings-store.ts: both main and this branch independently added a
  per-account default-identity (#507) migration at different versions (main v6,
  branch v7). Merged migration is version 7 using the refactored migrateSettings
  function; the unified-mailbox rework is guarded at `version < 7` so users who
  stopped at main's interim v6 identity bump still receive it, while the #507
  identity-map coercion stays at `version < 6` so their populated map is kept.
- stores/auth-store.ts: kept main's applyPreferredIdentity (superset with the
  pre-#507 legacy migration).
- stores/email-store.ts: removed the ALL_MAIL_MAILBOX_ID paths (folded into the
  unified views) while preserving main's plugin hooks (onSearchResults /
  onEmailsFetched); adopted advancedSearchCrossViewEmails for advanced cross-view
  search.
- components/settings/layout-settings.tsx: kept main's faviconUnreadBadge setting
  alongside the new unifiedCrossAccount toggle.
- integration/: union-merged the two independently-authored suites - branch suite
  is authoritative (matches new behavior) with main's shared-identity (#569) group
  infrastructure preserved.
- components/email/email-composer.tsx: dropped a duplicate data-testid attribute
  introduced by the auto-merge.
This commit is contained in:
Linus Rath
2026-07-16 19:57:51 +02:00
62 changed files with 2460 additions and 461 deletions
@@ -3,6 +3,7 @@ import { useEmailStore } from '../email-store';
import { useAuthStore } from '../auth-store';
import type { Email, Mailbox } from '@/lib/jmap/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
import type { UnifiedAccountClient } from '@/lib/unified-mailbox';
// Regression coverage for issue #281: single-email actions performed in the
// unified inbox must be routed to the *email's own account* client, not the
@@ -54,6 +55,8 @@ function makeClient() {
toggleStar: vi.fn().mockResolvedValue(undefined),
moveEmail: vi.fn().mockResolvedValue(undefined),
batchMarkAsRead: vi.fn().mockResolvedValue(undefined),
batchDeleteEmails: vi.fn().mockResolvedValue(undefined),
batchMoveEmails: vi.fn().mockResolvedValue(undefined),
} as unknown as IJMAPClient;
}
@@ -96,6 +99,9 @@ describe('unified-view single-email action routing (#281)', () => {
processingReadStatus: new Set(),
selectedEmail: null,
selectedEmailIds: new Set(),
unifiedScope: [],
unifiedCounts: [],
crossUnreadCount: 0,
emails: [
// Second direct login: sourceClientAccountId === sourceAccountId === 'account-b'.
makeEmail({ id: 'email-b', accountId: 'account-b', sourceClientAccountId: 'account-b', sourceAccountId: 'account-b', keywords: {}, mailboxIds: { 'b-inbox': true } }),
@@ -180,6 +186,96 @@ describe('unified-view single-email action routing (#281)', () => {
expect(activeClient.toggleStar).toHaveBeenCalledWith('email-shared', true, 'owner-x');
});
it('decrements a shared/group folder counter when deleting from the unified view', async () => {
// Real app: the active account's `mailboxes` includes its delegated shared
// folders (namespaced id + originalId + owner accountId). Unified-fetched
// shared emails carry the owner's BARE mailboxIds and sourceAccountId=owner.
// Regression: emailInMailbox missed these, so the shared folder's badge
// stayed at its old value after deleting in All mail / All unread.
useEmailStore.setState({
mailboxes: [
makeMailbox({ id: 'a-inbox', role: 'inbox', unreadEmails: 2, totalEmails: 5 }),
makeMailbox({
id: 'owner-x:x-inbox', originalId: 'x-inbox', name: 'Shared Inbox',
role: 'inbox', isShared: true, accountId: 'owner-x',
unreadEmails: 4, totalEmails: 10,
}),
],
emails: [
makeEmail({
id: 'email-shared', accountId: 'owner-x',
sourceClientAccountId: 'account-a', sourceAccountId: 'owner-x',
keywords: {}, // unread
mailboxIds: { 'x-inbox': true }, // BARE owner id (not namespaced)
}),
],
selectedEmailIds: new Set(['email-shared']),
});
await useEmailStore.getState().batchDelete(activeClient, true);
expect(activeClient.batchDeleteEmails).toHaveBeenCalledWith(['email-shared'], 'owner-x');
const shared = useEmailStore.getState().mailboxes.find(m => m.id === 'owner-x:x-inbox')!;
expect(shared.unreadEmails).toBe(3); // was 4
expect(shared.totalEmails).toBe(9); // was 10
});
it('decrements the unified-section badges when deleting from the unified view (live projection)', async () => {
// The unified-section badges (unifiedCounts / crossUnreadCount) must be a
// live projection of the per-account mailbox lists, NOT a stale server
// snapshot. Deleting a message in the unified view patches the folder's
// counter; the badge must follow in lockstep without a re-fetch.
const scope: UnifiedAccountClient[] = [
{
accountId: 'account-a', accountLabel: 'A', client: activeClient,
clientAccountId: 'account-a', jmapAccountId: 'account-a', isShared: false,
mailboxes: [makeMailbox({ id: 'a-inbox', role: 'inbox' })],
},
{
accountId: 'owner-x', accountLabel: 'Shared', client: activeClient,
clientAccountId: 'account-a', jmapAccountId: 'owner-x', isShared: true,
mailboxes: [makeMailbox({ id: 'owner-x:x-inbox', originalId: 'x-inbox', role: 'inbox', isShared: true, accountId: 'owner-x' })],
},
];
useEmailStore.setState({
mailboxes: [
makeMailbox({ id: 'a-inbox', role: 'inbox', unreadEmails: 2, totalEmails: 5 }),
makeMailbox({
id: 'owner-x:x-inbox', originalId: 'x-inbox', name: 'Shared Inbox',
role: 'inbox', isShared: true, accountId: 'owner-x',
unreadEmails: 4, totalEmails: 10,
}),
],
emails: [
makeEmail({
id: 'email-shared', accountId: 'owner-x',
sourceClientAccountId: 'account-a', sourceAccountId: 'owner-x',
keywords: {}, // unread
mailboxIds: { 'x-inbox': true }, // BARE owner id (not namespaced)
}),
],
selectedEmailIds: new Set(['email-shared']),
});
// Seed the badges from the scope (also stores unifiedScope).
useEmailStore.getState().refreshUnifiedCounts(scope);
useEmailStore.getState().refreshCrossCounts(scope);
const before = useEmailStore.getState();
expect(before.unifiedCounts.find(c => c.role === 'inbox')).toMatchObject({ unreadEmails: 6, totalEmails: 15 });
expect(before.crossUnreadCount).toBe(6);
await useEmailStore.getState().batchDelete(activeClient, true);
const after = useEmailStore.getState();
// Underlying folder counter dropped...
expect(after.mailboxes.find(m => m.id === 'owner-x:x-inbox')!.unreadEmails).toBe(3);
// ...and the unified-section badges followed via the live projection.
expect(after.unifiedCounts.find(c => c.role === 'inbox')).toMatchObject({ unreadEmails: 5, totalEmails: 14 });
expect(after.crossUnreadCount).toBe(5);
});
it('still uses the active/passed client outside unified view', async () => {
useEmailStore.setState({
isUnifiedView: false,
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { useSettingsStore } from '../settings-store';
import { useSettingsStore, migrateSettings } from '../settings-store';
describe('settings-store per-account allMailFolderIds', () => {
beforeEach(() => {
@@ -53,3 +53,43 @@ describe('settings-store per-account allMailFolderIds', () => {
});
});
});
describe('migrateSettings v5 -> v6 (Unified Mailbox rework)', () => {
it('keeps cross-account users cross-account when any cross view was on, and enables shared', () => {
const out = migrateSettings(
{ allMailFolderIds: {}, enableCrossUnreadView: true, enableAllMailView: false, includeGroupInUnified: false },
5,
) as unknown as Record<string, unknown>;
expect(out.unifiedCrossAccount).toBe(true);
// shared inclusion is enabled for every migrated config, even if it was off
expect(out.includeGroupInUnified).toBe(true);
expect(out.enableAllMailView).toBeUndefined();
});
it('folds a standalone All-Mail user into the account-bounded unified "All mail" entry', () => {
const out = migrateSettings(
{
allMailFolderIds: { 'acct-1': ['inbox', 'projects'] },
enableAllMailView: true,
enableUnifiedMailbox: false,
enableCrossUnreadView: false,
enableCrossStarredView: false,
enableCrossAllView: false,
},
5,
) as unknown as Record<string, unknown>;
expect(out.enableUnifiedMailbox).toBe(true);
expect(out.enableCrossAllView).toBe(true);
expect(out.unifiedCrossAccount).toBe(false); // new account-bounded default
expect(out.includeGroupInUnified).toBe(true);
// folder selection carries over unchanged -> narrows the unified lists
expect(out.allMailFolderIds).toEqual({ 'acct-1': ['inbox', 'projects'] });
expect(out.enableAllMailView).toBeUndefined();
});
it('a fresh user gets account-bounded defaults', () => {
const out = migrateSettings({ allMailFolderIds: {} }, 5) as unknown as Record<string, unknown>;
expect(out.unifiedCrossAccount).toBe(false);
expect(out.includeGroupInUnified).toBe(true);
});
});
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { useSettingsStore } from '../settings-store';
import { useSettingsStore, migrateSettings } from '../settings-store';
describe('settings-store per-account preferredIdentityIds (issue #507)', () => {
beforeEach(() => {
@@ -55,4 +55,27 @@ describe('settings-store per-account preferredIdentityIds (issue #507)', () => {
expect(useSettingsStore.getState().preferredIdentityIds).toEqual({ 'acct-9': 'a' });
});
});
describe('migrateSettings identity map', () => {
it('adds an empty preferredIdentityIds map for pre-v6 users', () => {
const out = migrateSettings({ allMailFolderIds: {} }, 6) as unknown as Record<string, unknown>;
expect(out.preferredIdentityIds).toEqual({});
});
it('coerces a non-record preferredIdentityIds to an empty map', () => {
const out = migrateSettings(
{ allMailFolderIds: {}, preferredIdentityIds: ['b'] },
7,
) as unknown as Record<string, unknown>;
expect(out.preferredIdentityIds).toEqual({});
});
it('preserves a valid per-account map across migration', () => {
const out = migrateSettings(
{ allMailFolderIds: {}, preferredIdentityIds: { 'acct-1': 'b' } },
7,
) as unknown as Record<string, unknown>;
expect(out.preferredIdentityIds).toEqual({ 'acct-1': 'b' });
});
});
});
+201 -114
View File
@@ -1,5 +1,5 @@
import { create } from "zustand";
import { Email, Mailbox, StateChange, ScheduledEmail, SendEmailResult, ALL_MAIL_MAILBOX_ID, isUnifiedMailboxId, isCrossViewId } from "@/lib/jmap/types";
import { Email, Mailbox, StateChange, ScheduledEmail, SendEmailResult, isUnifiedMailboxId, isCrossViewId } from "@/lib/jmap/types";
import type { UnifiedMailboxRole, CrossView } from "@/lib/jmap/types";
import type { IJMAPClient } from "@/lib/jmap/client-interface";
import { useSettingsStore } from "@/stores/settings-store";
@@ -7,7 +7,7 @@ import { useCalendarStore } from "@/stores/calendar-store";
import { SearchFilters, DEFAULT_SEARCH_FILTERS, buildJMAPFilter, isFilterEmpty } from "@/lib/jmap/search-utils";
import { emailHooks } from "@/lib/plugin-hooks";
import type { ExternalSearchResult } from "@/lib/plugin-types";
import { fetchUnifiedEmails, fetchUnifiedMailboxCounts, searchUnifiedEmails, advancedSearchUnifiedEmails, fetchCrossViewEmails, searchCrossViewEmails, getCrossUnreadTotal, resolveSourceFolderName, type UnifiedAccountClient, type UnifiedMailboxCounts } from "@/lib/unified-mailbox";
import { fetchUnifiedEmails, fetchUnifiedMailboxCounts, searchUnifiedEmails, advancedSearchUnifiedEmails, fetchCrossViewEmails, searchCrossViewEmails, advancedSearchCrossViewEmails, getCrossUnreadTotal, type UnifiedAccountClient, type UnifiedMailboxCounts } from "@/lib/unified-mailbox";
import { useAuthStore } from "@/stores/auth-store";
import { useAccountStore } from "@/stores/account-store";
@@ -82,9 +82,23 @@ interface EmailStore {
// isUnifiedView.
crossView: CrossView | null;
unifiedErrors: Map<string, string>; // accountId -> error message
// Unified-section sidebar badges. These are NOT an independent source of
// truth: they are a pure projection of the live per-account mailbox lists
// (`mailboxes` + `accountMailboxes`) over the last-known unified scope
// (`unifiedScope`). Recomputed automatically whenever those lists change (see
// the store subscription below), so optimistic delete/move/markRead patches and
// push-driven mailbox refreshes flow into the badges without a server round
// trip. (#281 follow-up: single source of truth for unified counters.)
unifiedCounts: UnifiedMailboxCounts[];
// Unread total across the cross-view included folders (badge for unread/all).
crossUnreadCount: number;
// The account/folder structure (which accounts, role mailboxes, cross-include
// selection) that the unified badges are projected over. Set by
// refreshUnifiedCounts/refreshCrossCounts from the freshly-built
// UnifiedAccountClient[]. The COUNTER values it carries are ignored at
// projection time - live counters are read from `mailboxes`/`accountMailboxes`
// instead - so a stale snapshot here only affects structure, never numbers.
unifiedScope: UnifiedAccountClient[];
// Scheduled send state
scheduledEmails: ScheduledEmail[];
@@ -330,34 +344,19 @@ function resolveActionMailboxes(): Mailbox[] {
}
/**
* Resolves the JMAP mailbox ids that make up the gated "All Mail" view for the
* active/viewing account. Honors that account's `allMailFolderIds` entry; when
* not configured it defaults to every non-special (no-role) folder. Shared
* folders are excluded - All Mail is scoped to a single account. Returns
* JMAP-side ids (originalId for namespaced mailboxes).
* Resolves the store-side mailbox ids that make up a personal account's
* contribution to the unified cross views (All mail / Unread / Starred), honoring
* that account's `allMailFolderIds` folder selection. Returns `undefined` when the
* account has no explicit selection, so the cross views fall back to their
* role-exclusion default (inbox + custom folders). An explicit `[]` selection
* yields an empty list (no own folders). `ownMailboxes` must already exclude
* shared folders - the picker only ever scopes the user's own folders.
*/
function resolveAllMailJmapIds(): string[] {
const mailboxes = resolveActionMailboxes().filter((mb) => !mb.isShared);
// Per-account selection: read the entry for the account the view is scoped to
// (the Pro viewing override, else the global active account). A missing entry
// = "not configured" -> all no-role folders; an explicit [] = no folders.
const accountId = useEmailStore.getState().viewingAccountId ?? useAuthStore.getState().activeAccountId;
const configured = accountId ? useSettingsStore.getState().allMailFolderIds[accountId] : undefined;
const selected = configured === undefined
? mailboxes.filter((mb) => !mb.role)
: mailboxes.filter((mb) => configured.includes(mb.id));
return selected.map((mb) => mb.originalId || mb.id);
}
/**
* Builds the JMAP Email/query filter for the All Mail view from a set of
* mailbox ids - an OR of `inMailbox` conditions (or a single condition).
*/
function buildAllMailFilter(jmapMailboxIds: string[]): Record<string, unknown> {
if (jmapMailboxIds.length === 1) {
return { inMailbox: jmapMailboxIds[0] };
}
return { operator: 'OR', conditions: jmapMailboxIds.map((id) => ({ inMailbox: id })) };
function resolveCrossIncludedMailboxIds(accountId: string, ownMailboxes: Mailbox[]): string[] | undefined {
const configured = useSettingsStore.getState().allMailFolderIds[accountId];
if (configured === undefined) return undefined;
const selected = new Set(configured);
return ownMailboxes.filter((mb) => selected.has(mb.id)).map((mb) => mb.id);
}
/**
@@ -418,12 +417,24 @@ function resolveEmailActionContext(
* owner account reachable through each logged-in client. The shared entries
* are flagged with `isShared: true` so `lib/unified-mailbox.ts` routes JMAP
* requests via `originalId` + owner accountId.
*
* When `scopeToClientAccountId` is set, only the matching logged-in account
* (and the shared owners reachable through its client) is built - this keeps
* the unified mailbox within a single account boundary. Omitting it spans every
* logged-in account (the cross-account sub-option).
*
* Personal entries carry `crossIncludedMailboxIds` derived from the account's
* `allMailFolderIds` folder selection, restricting the All mail / Unread /
* Starred cross views to the chosen own folders (shared entries are left
* unrestricted so all their folders are included).
*/
export async function buildUnifiedAccountClients(
opts: { includeGroup?: boolean } = {},
opts: { includeGroup?: boolean; scopeToClientAccountId?: string } = {},
): Promise<UnifiedAccountClient[]> {
const { includeGroup = false } = opts;
const authAccounts = useAccountStore.getState().accounts.filter((a) => a.isConnected);
const { includeGroup = false, scopeToClientAccountId } = opts;
const authAccounts = useAccountStore.getState().accounts.filter(
(a) => a.isConnected && (!scopeToClientAccountId || a.id === scopeToClientAccountId),
);
const allClients = useAuthStore.getState().getAllConnectedClients();
const built: UnifiedAccountClient[] = [];
// Per-account mailbox lists gathered here are cached into `accountMailboxes`
@@ -443,7 +454,7 @@ export async function buildUnifiedAccountClients(
// no-op (no namespacing) — keeps personal behavior identical while making
// resolution branch-free against shared sources.
const primaryJmapId = c.getAccountId();
built.push({ accountId: a.id, accountLabel: a.label || a.email, client: c, mailboxes: ownMailboxes, clientAccountId: a.id, jmapAccountId: primaryJmapId, isShared: false });
built.push({ accountId: a.id, accountLabel: a.label || a.email, client: c, mailboxes: ownMailboxes, clientAccountId: a.id, jmapAccountId: primaryJmapId, isShared: false, crossIncludedMailboxIds: resolveCrossIncludedMailboxIds(a.id, ownMailboxes) });
fetchedMailboxes[a.id] = ownMailboxes;
// Also cache under the JMAP id so `accountMailboxes[email.sourceAccountId]`
// resolves uniformly for personal and shared sources alike.
@@ -510,19 +521,31 @@ async function refreshMailboxesForViewingAccount(fallbackClient: IJMAPClient): P
}
// Whether an email belongs to a given mailbox, for local counter math.
// Shared/group-account emails carry NAMESPACED mailboxIds (`${ownerId}:${origId}`,
// which equals the shared mailbox's `id`), while own-account emails carry bare ids
// (equal to both `id` and `originalId`). Matching `mailbox.id` covers both; the
// `originalId` fallback is restricted to non-shared mailboxes so a bare own-account
// id can't collide with another account's shared folder. (#281)
// Own-account emails carry bare ids (equal to both `id` and `originalId`).
// As of #281 V3, EVERY client fetch path (getEmails/getEmail/getThreadEmails/
// searchEmails/advancedSearchEmails) namespaces shared/delegated emails'
// `mailboxIds` to the store id (`${ownerId}:${origId}`), so the `ids[mailbox.id]`
// fast path below matches own and shared mailboxes alike - one id space.
// The `originalId` branches remain as a defensive fallback for any email that
// still carries a bare owner id (scoped to the owning account via
// `sourceAccountId === mailbox.accountId` so a bare owner id can't collide with
// another account's folder). (#281)
function emailInMailbox(
email: { mailboxIds?: Record<string, boolean> },
email: { mailboxIds?: Record<string, boolean>; sourceAccountId?: string },
mailbox: Mailbox,
): boolean {
const ids = email.mailboxIds;
if (!ids) return false;
if (ids[mailbox.id]) return true;
if (!mailbox.isShared && mailbox.originalId) return !!ids[mailbox.originalId];
if (
mailbox.isShared &&
mailbox.originalId &&
email.sourceAccountId &&
email.sourceAccountId === mailbox.accountId
) {
return !!ids[mailbox.originalId];
}
return false;
}
@@ -639,6 +662,62 @@ function applyDeleteCounters(
};
}
// ─── Unified-badge live projection ────────────────────────────────────────────
//
// The unified-section badges (unifiedCounts / crossUnreadCount) are a pure
// projection of the live per-account mailbox lists - the SAME lists the
// optimistic delete/move/markRead paths patch and that push refreshes. Rather
// than trusting the counter snapshot baked into the UnifiedAccountClient[] (which
// came from a server fetch and goes stale the moment a local mutation runs), we
// look each scope mailbox up by id in the live store list and use its current
// counters. This keeps the badges in lockstep with the per-folder counters - one
// source of truth, no server round trip, no eventual-consistency snap-back.
// The live store list that holds a unified-scope account's folders. Mirrors
// applyMailboxCounterUpdate's routing exactly: the active client's folders (incl.
// its delegated shared folders) live in `mailboxes`; every other logged-in
// account's folders live in `accountMailboxes[clientAccountId]`. Falls back to
// the account's own (snapshot) list so an unknown account still contributes its
// last-known counters instead of vanishing.
function liveListForAccount(
account: UnifiedAccountClient,
state: { mailboxes: Mailbox[]; accountMailboxes: Record<string, Mailbox[]> },
): Mailbox[] {
const activeId = useAuthStore.getState().activeAccountId;
if (account.clientAccountId === activeId) return state.mailboxes;
return state.accountMailboxes[account.clientAccountId] ?? account.mailboxes;
}
// Returns a shallow copy of the scope account whose mailboxes carry LIVE counter
// values (matched by id against the live store list). Structure - which
// mailboxes, their roles, originalId, crossIncludedMailboxIds - is preserved from
// the scope snapshot; only the counter numbers are refreshed. This lets the
// existing lib aggregators (fetchUnifiedMailboxCounts / getCrossUnreadTotal) run
// unchanged over live data.
function accountWithLiveCounters(
account: UnifiedAccountClient,
state: { mailboxes: Mailbox[]; accountMailboxes: Record<string, Mailbox[]> },
): UnifiedAccountClient {
const live = liveListForAccount(account, state);
const byId = new Map(live.map((m) => [m.id, m]));
return { ...account, mailboxes: account.mailboxes.map((m) => byId.get(m.id) ?? m) };
}
// Project the live mailbox state over the current unified scope into the two
// badge values. Pure function of (unifiedScope, mailboxes, accountMailboxes).
function projectUnifiedCounts(
state: { unifiedScope: UnifiedAccountClient[]; mailboxes: Mailbox[]; accountMailboxes: Record<string, Mailbox[]> },
): { unifiedCounts: UnifiedMailboxCounts[]; crossUnreadCount: number } {
if (state.unifiedScope.length === 0) {
return { unifiedCounts: [], crossUnreadCount: 0 };
}
const live = state.unifiedScope.map((a) => accountWithLiveCounters(a, state));
return {
unifiedCounts: fetchUnifiedMailboxCounts(live),
crossUnreadCount: getCrossUnreadTotal(live),
};
}
// Find the trash mailbox for a given account scope. Prefers JMAP role, but
// falls back to name matching ("trash" / "deleted") so users with custom or
// pre-existing folders (e.g. "Deleted Items") aren't silently destroyed.
@@ -706,6 +785,7 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
unifiedErrors: new Map(),
unifiedCounts: [],
crossUnreadCount: 0,
unifiedScope: [],
// Scheduled send state
scheduledEmails: [],
@@ -871,7 +951,6 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
// doesn't exist in the fetched list (e.g. after an account switch)
const currentSelectedMailbox = get().selectedMailbox;
const selectionValid = currentSelectedMailbox === VIRTUAL_SCHEDULED_MAILBOX_ID
|| currentSelectedMailbox === ALL_MAIL_MAILBOX_ID
// Unified per-role views (All Inbox/Drafts/Junk/…) and cross-account views
// (All unread/starred/all) use a virtual id not present in the fetched
// list. A background refresh after a delete must not clobber it and jump
@@ -935,29 +1014,6 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
await get().fetchScheduledEmails(client);
return;
}
if (targetMailboxId === ALL_MAIL_MAILBOX_ID) {
const jmapIds = resolveAllMailJmapIds();
if (jmapIds.length === 0) {
set({ emails: [], hasMoreEmails: false, totalEmails: 0, isLoading: false });
return;
}
const emailsPerPage = useSettingsStore.getState().emailsPerPage;
const result = await resolveActionClient(client).advancedSearchEmails(
buildAllMailFilter(jmapIds), undefined, emailsPerPage, 0,
);
const allMailMailboxes = resolveActionMailboxes();
for (const email of result.emails) {
email.sourceFolder = resolveSourceFolderName(email, allMailMailboxes);
}
const enrichedEmails = await emailHooks.onEmailsFetched.transform(result.emails);
set({
emails: annotateScheduledEmails(enrichedEmails, get().scheduledSubmissionByEmailId),
hasMoreEmails: result.hasMore,
totalEmails: result.total,
isLoading: false,
});
return;
}
const effectiveClient = resolveActionClient(client);
// Find the mailbox to get its accountId (for shared folder support)
@@ -1018,9 +1074,12 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
const includeGroup = useSettingsStore.getState().includeGroupInUnified;
const position = emails.length;
const built = await buildUnifiedAccountClients({ includeGroup });
const result = searchQuery
? await searchCrossViewEmails(built, crossView, searchQuery, emailsPerPage, position)
: await fetchCrossViewEmails(built, crossView, emailsPerPage, position);
const hasFilters = !isFilterEmpty(get().searchFilters);
const result = hasFilters
? await advancedSearchCrossViewEmails(built, crossView, buildJMAPFilter(searchQuery, get().searchFilters, undefined), emailsPerPage, position)
: searchQuery
? await searchCrossViewEmails(built, crossView, searchQuery, emailsPerPage, position)
: await fetchCrossViewEmails(built, crossView, emailsPerPage, position);
const currentEmails = get().emails;
const existingIds = new Set(currentEmails.map(e => e.id));
const newEmails = result.emails.filter(e => !existingIds.has(e.id));
@@ -1106,21 +1165,7 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
const { searchFilters } = get();
const hasFilters = !isFilterEmpty(searchFilters);
if (selectedMailbox === ALL_MAIL_MAILBOX_ID) {
if (searchQuery || hasFilters) {
// Search within All Mail spans the whole account (no inMailbox).
result = hasFilters
? await effectiveClient.advancedSearchEmails(buildJMAPFilter(searchQuery, searchFilters, undefined), undefined, emailsPerPage, position)
: await effectiveClient.searchEmails(searchQuery, undefined, undefined, emailsPerPage, position);
} else {
const jmapIds = resolveAllMailJmapIds();
if (jmapIds.length === 0) {
set({ hasMoreEmails: false, isLoadingMore: false });
return;
}
result = await effectiveClient.advancedSearchEmails(buildAllMailFilter(jmapIds), undefined, emailsPerPage, position);
}
} else if (searchQuery || hasFilters) {
if (searchQuery || hasFilters) {
const mailboxes = resolveActionMailboxes();
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
const jmapMailboxId = mailbox?.originalId || selectedMailbox;
@@ -1146,13 +1191,6 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
result = await effectiveClient.getEmails(selectedKeyword ? undefined : jmapMailboxId, accountId, emailsPerPage, position, selectedKeyword ? `$label:${selectedKeyword}` : undefined, true);
}
if (selectedMailbox === ALL_MAIL_MAILBOX_ID) {
const allMailMailboxes = resolveActionMailboxes();
for (const email of result.emails) {
email.sourceFolder = resolveSourceFolderName(email, allMailMailboxes);
}
}
// Use fresh state when merging to avoid overwriting concurrent updates
// (e.g. refreshCurrentMailbox running during the load)
const currentEmails = get().emails;
@@ -1815,24 +1853,22 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
unifiedErrors = result.errors;
} else {
// Get the current mailbox to scope the search. In the All Mail view the
// search spans every folder of the account (no inMailbox constraint).
const isAllMail = selectedMailbox === ALL_MAIL_MAILBOX_ID;
// Get the current mailbox to scope the search.
const mailboxes = resolveActionMailboxes();
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
// Use originalId for shared mailboxes
const jmapMailboxId = isAllMail ? undefined : (mailbox?.originalId || selectedMailbox);
const jmapMailboxId = mailbox?.originalId || selectedMailbox;
// Only pass accountId for shared mailboxes, not for primary account
accountId = isAllMail ? undefined : (mailbox?.isShared ? mailbox.accountId : undefined);
accountId = mailbox?.isShared ? mailbox.accountId : undefined;
result = await resolveActionClient(client).searchEmails(query, jmapMailboxId, accountId, emailsPerPage, 0);
}
const hookEdit = await emailHooks.onSearchResults.transform({
newEmailIds: [] as string[],
result: result,
query: query,
filters: searchFilters
const hookEdit = await emailHooks.onSearchResults.transform({
newEmailIds: [] as string[],
result: result,
query: query,
filters: searchFilters
});
result = hookEdit.result;
@@ -1843,7 +1879,7 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
result.total += newEmails.length;
}
const externals = await emailHooks.onProvideSearchResults.transform([] as ExternalSearchResult[], {
const externals = await emailHooks.onProvideSearchResults.transform([] as ExternalSearchResult[], {
query,
filters: searchFilters
});
@@ -1895,7 +1931,11 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
if (isUnifiedView && crossView) {
const includeGroup = useSettingsStore.getState().includeGroupInUnified;
const built = await buildUnifiedAccountClients({ includeGroup });
result = await searchCrossViewEmails(built, crossView, searchQuery, emailsPerPage, 0);
// Cross views apply the advanced filter (text + fields) on top of the
// view membership; an empty filter degrades to a plain membership query.
result = await advancedSearchCrossViewEmails(
built, crossView, buildJMAPFilter(searchQuery, searchFilters, undefined), emailsPerPage, 0,
);
unifiedErrors = result.errors;
} else if (isUnifiedView && unifiedRole) {
@@ -1911,10 +1951,9 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
unifiedErrors = result.errors;
} else {
const isAllMail = selectedMailbox === ALL_MAIL_MAILBOX_ID;
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
const jmapMailboxId = isAllMail ? undefined : (mailbox?.originalId || selectedMailbox);
accountId = isAllMail ? undefined : (mailbox?.isShared ? mailbox.accountId : undefined);
const jmapMailboxId = mailbox?.originalId || selectedMailbox;
accountId = mailbox?.isShared ? mailbox.accountId : undefined;
const filter = buildJMAPFilter(searchQuery, searchFilters, jmapMailboxId);
result = await resolveActionClient(client).advancedSearchEmails(filter, accountId, emailsPerPage, 0);
@@ -2624,30 +2663,37 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
// Get the current account ID from the client (assuming primary account)
const accountId = client.getAccountId();
// Check if there are changes for this account
// Changes may arrive for the client's primary account OR a delegated
// shared/group owner it has access to. Active-account *view* concerns
// (current email list, scheduled, calendar, filters) key off the primary
// account only, but the mailbox-COUNT refresh must react to any changed
// account: the active client's getAllMailboxes returns own + delegated
// folders, and the unified-section counts project from that list. (#281)
const accountChanges = change.changed[accountId];
if (!accountChanges) return;
const anyMailboxChanged = Object.values(change.changed).some((c) => c?.Mailbox);
// Handle Email state changes - refresh current mailbox
if (accountChanges.Email) {
if (accountChanges?.Email) {
await get().refreshCurrentMailbox(client);
get().fetchTagCounts(client);
}
if (accountChanges.EmailSubmission) {
if (accountChanges?.EmailSubmission) {
await get().refreshScheduledMetadata(client);
if (get().isScheduledView) {
await get().fetchScheduledEmails(client);
}
}
// Handle Mailbox state changes - refresh mailbox list
if (accountChanges.Mailbox) {
// Handle Mailbox state changes - refresh mailbox list (own + delegated
// shared folders), so both the active account's and its shared folders'
// counters follow background activity.
if (anyMailboxChanged) {
await get().fetchMailboxes(client);
}
// Handle Calendar/CalendarEvent state changes - refresh calendar data
if (accountChanges.Calendar || accountChanges.CalendarEvent) {
if (accountChanges?.Calendar || accountChanges?.CalendarEvent) {
const calendarStore = useCalendarStore.getState();
if (calendarStore.supportsCalendar) {
calendarStore.fetchCalendars(client);
@@ -2665,7 +2711,7 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
}
// Handle SieveScript state changes - refresh filter rules
if (accountChanges.SieveScript) {
if (accountChanges?.SieveScript) {
const { useFilterStore } = await import('./filter-store');
const filterStore = useFilterStore.getState();
if (filterStore.isSupported) {
@@ -3293,8 +3339,13 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
refreshUnifiedCounts: async (accounts) => {
try {
const counts = fetchUnifiedMailboxCounts(accounts);
set({ unifiedCounts: counts });
// Store the scope and project live counters over it. The badges then track
// the live mailbox lists via the store subscription (below), so subsequent
// optimistic mutations update them without another build/fetch.
set((state) => {
const next = { ...state, unifiedScope: accounts };
return { unifiedScope: accounts, ...projectUnifiedCounts(next) };
});
} catch (error) {
console.error('Failed to refresh unified counts:', error);
}
@@ -3333,7 +3384,10 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
refreshCrossCounts: (accounts) => {
try {
set({ crossUnreadCount: getCrossUnreadTotal(accounts) });
set((state) => {
const next = { ...state, unifiedScope: accounts };
return { unifiedScope: accounts, ...projectUnifiedCounts(next) };
});
} catch (error) {
console.error('Failed to refresh cross-account counts:', error);
}
@@ -3355,6 +3409,11 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
selectedMailbox: isScheduledView ? VIRTUAL_SCHEDULED_MAILBOX_ID : leavingScheduled ? "" : state.selectedMailbox,
selectedEmail: leavingScheduled ? null : state.selectedEmail,
selectedEmailIds: leavingScheduled ? new Set<string>() : state.selectedEmailIds,
// Search is unavailable in the scheduled view (the input is disabled there).
// Reset any active search when entering it so a stale query can't linger or
// re-run when the user leaves again.
searchQuery: isScheduledView ? "" : state.searchQuery,
searchFilters: isScheduledView ? { ...DEFAULT_SEARCH_FILTERS } : state.searchFilters,
};
}),
clearPendingUndoSend: () => set({ pendingUndoSend: null }),
@@ -3730,3 +3789,31 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
});
},
}));
// Keep the unified-section badges in lockstep with the live per-account mailbox
// lists. Whenever `mailboxes`, `accountMailboxes`, or the unified scope change -
// i.e. after any optimistic delete/move/markRead patch or a push-driven mailbox
// refresh - re-project the badges from that single source of truth. The guard
// short-circuits on every unrelated state change (emails, loading flags, …) by
// reference equality, and our own counter writes don't re-enter the projection
// because they leave the three watched lists untouched (no loop). (#281)
useEmailStore.subscribe((state, prev) => {
if (
state.mailboxes === prev.mailboxes &&
state.accountMailboxes === prev.accountMailboxes &&
state.unifiedScope === prev.unifiedScope
) {
return;
}
if (state.unifiedScope.length === 0) return;
const projected = projectUnifiedCounts(state);
const sameCross = projected.crossUnreadCount === state.crossUnreadCount;
const sameUnified =
projected.unifiedCounts.length === state.unifiedCounts.length &&
projected.unifiedCounts.every((c, i) => {
const cur = state.unifiedCounts[i];
return cur && cur.role === c.role && cur.unreadEmails === c.unreadEmails && cur.totalEmails === c.totalEmails;
});
if (sameCross && sameUnified) return;
useEmailStore.setState(projected);
});
+77 -41
View File
@@ -233,22 +233,26 @@ interface SettingsState {
// Unified Mailbox
enableUnifiedMailbox: boolean;
// Include shared/delegated folders in the unified mailbox. Default true: the
// account-bounded unified view is defined by spanning the account's own folders
// plus every shared folder it can access.
includeGroupInUnified: boolean;
// When true, the unified mailbox merges across every logged-in account
// (cross-account). When false (default for new installs) it stays within the
// active account boundary (own + shared folders). Gated by the admin
// `unifiedCrossAccountEnabled` feature.
unifiedCrossAccount: boolean;
// All Mail view (gated): user toggle (like the unified mailbox) plus the set
// of folder ids merged into the virtual "All Mail" mailbox. `null` = never
// configured, in which case the view defaults to all non-special (no-role)
// folders of the active account.
enableAllMailView: boolean;
// Cross-account "All accounts" views (gated per-view by the admin policy)
// Unified Mailbox entries, each gated per-view by the admin policy. These show
// the All mail / Unread / Starred lists, scoped by `unifiedCrossAccount` and
// narrowed by the `allMailFolderIds` folder selection.
enableCrossUnreadView: boolean;
enableCrossStarredView: boolean;
enableCrossAllView: boolean;
// Per-account "All Mail" folder selection, keyed by AccountEntry.id. A
// missing entry = "not configured" -> defaults to every no-role folder; an
// explicit [] = "no folders". (Replaced the legacy global string[] | null.)
// Per-account folder selection narrowing the unified All mail / Unread /
// Starred lists, keyed by AccountEntry.id. A missing entry = "not configured"
// -> defaults to inbox + custom folders; an explicit [] = "no own folders".
allMailFolderIds: Record<string, string[]>;
// Per-account default sender identity, keyed by AccountEntry.id -> JMAP
@@ -444,10 +448,9 @@ const DEFAULT_SETTINGS = {
// Unified Mailbox
enableUnifiedMailbox: false,
includeGroupInUnified: false,
includeGroupInUnified: true,
unifiedCrossAccount: false,
// All Mail view (gated)
enableAllMailView: false,
allMailFolderIds: {} as Record<string, string[]>,
preferredIdentityIds: {} as Record<string, string>,
@@ -633,7 +636,7 @@ export const useSettingsStore = create<SettingsState>()(
// (see DEVICE_LOCAL_SETTING_KEYS) and must not be synced.
enableUnifiedMailbox: state.enableUnifiedMailbox,
includeGroupInUnified: state.includeGroupInUnified,
enableAllMailView: state.enableAllMailView,
unifiedCrossAccount: state.unifiedCrossAccount,
allMailFolderIds: state.allMailFolderIds,
preferredIdentityIds: state.preferredIdentityIds,
enableCrossUnreadView: state.enableCrossUnreadView,
@@ -893,9 +896,36 @@ export const useSettingsStore = create<SettingsState>()(
}),
{
name: 'settings-storage',
version: 6,
migrate: (persisted, version) => {
const state = persisted as Record<string, unknown>;
version: 7,
migrate: migrateSettings,
onRehydrateStorage: () => {
return (state) => {
if (state) {
// Defensive: a legacy global array or any non-record value (e.g.
// synced from an older client) is coerced to an empty map so
// per-account consumers never see a non-record.
if (!isPlainRecord(state.allMailFolderIds)) {
state.allMailFolderIds = {};
}
if (!isPlainRecord(state.preferredIdentityIds)) {
state.preferredIdentityIds = {};
}
applyFontSize(state.fontSize);
applyDensity(state.density);
applyAnimations(state.animationsEnabled);
}
};
},
}
)
);
/**
* Versioned migration for persisted settings. Exported for tests. Mutates and
* returns the persisted record so each bump only needs to handle its own delta.
*/
export function migrateSettings(persisted: unknown, version: number): SettingsState {
const state = persisted as Record<string, unknown>;
if (version < 2 && state.listDensity) {
state.density = state.listDensity;
delete state.listDensity;
@@ -921,34 +951,40 @@ export const useSettingsStore = create<SettingsState>()(
if (version < 5 || !isPlainRecord(state.allMailFolderIds)) {
state.allMailFolderIds = {};
}
// v6: introduced the per-account default-identity map (issue #507).
// Coerce any missing/legacy value to an empty record.
// "All accounts" was reworked into the account-bounded "Unified
// Mailbox". The standalone __all_mail__ view (`enableAllMailView`) was
// folded into the unified "All mail" entry (`enableCrossAllView`), and a
// `unifiedCrossAccount` toggle now governs whether the views span every
// logged-in account. Existing users keep their current behaviour:
// - if any cross view was on, they were already cross-account -> keep it on
// - else if only standalone All Mail was on, enable the account-bounded
// unified "All mail" entry (folder selection carries over via allMailFolderIds)
// Guarded at <7 (not <6) so users who stopped at main's interim v6
// identity-map bump - which shipped without this rework - still receive it.
if (version < 7) {
const hadCross = !!(state.enableCrossUnreadView || state.enableCrossStarredView || state.enableCrossAllView);
if (hadCross) {
state.unifiedCrossAccount = true;
} else if (state.enableAllMailView) {
state.enableUnifiedMailbox = true;
state.enableCrossAllView = true;
state.unifiedCrossAccount = false;
}
delete state.enableAllMailView;
if (typeof state.unifiedCrossAccount !== 'boolean') state.unifiedCrossAccount = false;
// The reworked unified mailbox spans the account's own folders plus its
// shared/group folders, so enable shared inclusion for every migrated
// configuration (matches the new-install default).
state.includeGroupInUnified = true;
}
// Per-account default-identity map (issue #507). Coerce any
// missing/legacy value to an empty record. Guarded at <6 so users who
// already received it via main's v6 bump keep their populated map.
if (version < 6 || !isPlainRecord(state.preferredIdentityIds)) {
state.preferredIdentityIds = {};
}
return state as unknown as SettingsState;
},
onRehydrateStorage: () => {
return (state) => {
if (state) {
// Defensive: a legacy global array or any non-record value (e.g.
// synced from an older client) is coerced to an empty map so
// per-account consumers never see a non-record.
if (!isPlainRecord(state.allMailFolderIds)) {
state.allMailFolderIds = {};
}
if (!isPlainRecord(state.preferredIdentityIds)) {
state.preferredIdentityIds = {};
}
applyFontSize(state.fontSize);
applyDensity(state.density);
applyAnimations(state.animationsEnabled);
}
};
},
}
)
);
}
// Helper functions to apply settings to DOM
function applyFontSize(size: FontSize) {