feat(unified-mailbox): account-bounded Unified Mailbox with opt-in cross-account

Rework the sidebar "All accounts" section into a "Unified Mailbox" that, by
default, stays within the active login account and its shared/group folders.
Merging across multiple logged-in accounts becomes an opt-in sub-option instead
of the default, and the standalone per-account "All Mail" virtual folder is
folded into the unified All mail / Unread / Starred entries (its folder selection
now narrows those lists).

Scope:
- lib/unified-mailbox.ts: UnifiedAccountClient.crossIncludedMailboxIds; the cross
  views honor the per-account folder selection (union across accounts = the sum
  of each account's selection), falling back to inbox+custom when unset.
- stores/email-store.ts: buildUnifiedAccountClients gains scopeToClientAccountId
  (the account boundary) and populates crossIncludedMailboxIds from
  allMailFolderIds; remove the standalone __all_mail__ fetch/search/load-more
  branches.
- page.tsx: scope to the active account unless cross-account is active (per-user
  opt-in AND admin gate); the per-role unified mailboxes obey the same scope.

Folding:
- Drop ALL_MAIL_MAILBOX_ID (lib/jmap/types.ts); thread-list source-folder column
  now keys on isUnifiedView only; settings folder picker moves under the unified
  group and shows once any unified entry is enabled.

Config:
- User: new unifiedCrossAccount (default false); includeGroupInUnified default
  flips to true; enableAllMailView retired; the three cross-view toggles now gate
  the unified Unread/Starred/All mail entries.
- Admin: new unifiedCrossAccountEnabled gate, default FALSE (cross-account is an
  admin opt-in; when off the per-user toggle is hidden and the scope is forced
  account-bounded at runtime). allMailViewEnabled deprecated and normalized
  forward into crossAllViewEnabled on policy load; cross-view gate labels reworded
  to "Unified Mailbox: ...".

Header: the sidebar section shows "All accounts" when cross-account is active
(opt-in AND admin gate AND >1 connected account), else "Unified Mailbox".

Migration:
- Settings persist v5 -> v6 (exported migrateSettings) - cross-active users keep
  cross-account; All-Mail-only users get the account-bounded unified All mail
  entry with folder ids preserved; includeGroupInUnified enabled for every
  migrated config; fresh installs are account-bounded.
- Admin policy: one-shot, marker-guarded migratePolicyUnifiedMailbox (run before
  configManager.load) enables unifiedCrossAccountEnabled when a cross view was
  active, so existing cross-account installs keep the behaviour despite the
  default-false gate. Skipped on read-only config dirs.

Locales: sidebar all_accounts (original label) + unified_mailbox (translated, per
locale) keys; dead standalone all_mail strings removed across all 20 locales.

Docs: FEATURES.md updated to the account-bounded model, the cross-account gate,
and the folder-narrowed aggregate entries.

Verification: tsc clean, eslint clean, full vitest suite green (incl. translations
completeness, cross-view/migration coverage, and the admin policy migration test).
This commit is contained in:
Stefan Hildebrandt
2026-07-11 21:14:34 +02:00
parent 38a396d150
commit 7c221c4a4a
37 changed files with 541 additions and 257 deletions
@@ -42,6 +42,26 @@ describe('getCrossIncludedMailboxes', () => {
const ids = getCrossIncludedMailboxes(account).map((m) => m.id);
expect(ids).toEqual(['inbox', 'projects']);
});
it('honors an explicit crossIncludedMailboxIds selection (folder picker)', () => {
const account = makeAccount({
accountId: 'a',
mailboxes: [mb('inbox', 'inbox'), mb('projects', undefined), mb('archive', 'archive')],
// user picked inbox + archive, excluded projects - overrides role exclusion
crossIncludedMailboxIds: ['inbox', 'archive'],
});
const ids = getCrossIncludedMailboxes(account).map((m) => m.id);
expect(ids).toEqual(['inbox', 'archive']);
});
it('an empty selection yields no folders', () => {
const account = makeAccount({
accountId: 'a',
mailboxes: [mb('inbox', 'inbox'), mb('projects', undefined)],
crossIncludedMailboxIds: [],
});
expect(getCrossIncludedMailboxes(account)).toEqual([]);
});
});
describe('buildCrossFilter', () => {
@@ -86,6 +106,22 @@ describe('getCrossUnreadTotal', () => {
});
expect(getCrossUnreadTotal([a, b])).toBe(10);
});
it('counts only the selected folders when crossIncludedMailboxIds is set; shared accounts stay unrestricted', () => {
// personal account narrowed to inbox only (projects excluded by the picker)
const personal = makeAccount({
accountId: 'a',
mailboxes: [mb('inbox', 'inbox', 3), mb('projects', undefined, 4)],
crossIncludedMailboxIds: ['inbox'],
});
// shared account unrestricted -> role-exclusion default (inbox + custom)
const shared = makeAccount({
accountId: 'owner',
isShared: true,
mailboxes: [mb('ns:inbox', 'inbox', 5, 'orig-inbox'), mb('ns:team', undefined, 2, 'orig-team'), mb('ns:junk', 'junk', 9, 'orig-junk')],
});
expect(getCrossUnreadTotal([personal, shared])).toBe(3 + 5 + 2);
});
});
describe('resolveSourceFolderName', () => {
@@ -0,0 +1,59 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, rm, readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { migratePolicyUnifiedMailbox } from '../migrate';
// migratePolicyUnifiedMailbox reads ADMIN_CONFIG_DIR at call time (see paths.ts),
// so each test points it at a fresh temp dir.
let dir: string;
const policyPath = () => path.join(dir, 'policy.json');
const markerPath = () => path.join(dir, '.migrated-unified-mailbox');
const writePolicy = (features: Record<string, unknown>) =>
writeFile(policyPath(), JSON.stringify({ features, restrictions: {} }, null, 2), 'utf-8');
const readFeatures = async () =>
JSON.parse(await readFile(policyPath(), 'utf-8')).features as Record<string, unknown>;
beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), 'bw-policy-'));
process.env.ADMIN_CONFIG_DIR = dir;
});
afterEach(async () => {
delete process.env.ADMIN_CONFIG_DIR;
await rm(dir, { recursive: true, force: true });
});
describe('migratePolicyUnifiedMailbox', () => {
it('enables unifiedCrossAccountEnabled when a cross view was active', async () => {
await writePolicy({ crossUnreadViewEnabled: true });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(true);
expect(existsSync(markerPath())).toBe(true);
});
it('does not enable it for a standalone All-Mail-only policy', async () => {
await writePolicy({ allMailViewEnabled: true, crossUnreadViewEnabled: false, crossStarredViewEnabled: false, crossAllViewEnabled: false });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBeUndefined();
});
it('is a one-shot: a later admin disable survives a re-run', async () => {
await writePolicy({ crossAllViewEnabled: true });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(true);
// Admin turns it back off; the marker is present, so re-running is a no-op.
await writePolicy({ crossAllViewEnabled: true, unifiedCrossAccountEnabled: false });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(false);
});
it('no policy.json: writes the marker and does not throw', async () => {
await migratePolicyUnifiedMailbox();
expect(existsSync(markerPath())).toBe(true);
expect(existsSync(policyPath())).toBe(false);
});
});
+17 -4
View File
@@ -33,12 +33,12 @@ class ConfigManager {
this.adminConfig = await this.readJsonFile('config.json') || {};
const policy = await this.readJsonFile('policy.json');
if (policy) {
this.policyCache = {
this.policyCache = ConfigManager.normalizePolicy({
...DEFAULT_POLICY,
...policy,
features: { ...DEFAULT_FEATURE_GATES, ...(policy.features || {}) },
themePolicy: { ...DEFAULT_THEME_POLICY, ...(policy.themePolicy || {}) },
};
});
} else {
this.policyCache = { ...DEFAULT_POLICY };
}
@@ -166,15 +166,28 @@ class ConfigManager {
*/
async setPolicy(policy: SettingsPolicy): Promise<void> {
assertWritable('update settings policy');
this.policyCache = {
this.policyCache = ConfigManager.normalizePolicy({
...DEFAULT_POLICY,
...policy,
features: { ...DEFAULT_FEATURE_GATES, ...(policy.features || {}) },
themePolicy: { ...DEFAULT_THEME_POLICY, ...(policy.themePolicy || {}) },
};
});
await this.writeJsonFile('policy.json', this.policyCache as unknown as Record<string, unknown>);
}
/**
* Migrates deprecated feature gates forward. The standalone "All Mail" view
* (`allMailViewEnabled`) was folded into the unified "All mail" entry, so an
* admin who enabled it keeps that entry available via `crossAllViewEnabled`.
* Idempotent - safe to run on every load.
*/
private static normalizePolicy(policy: SettingsPolicy): SettingsPolicy {
if (policy.features.allMailViewEnabled) {
policy.features.crossAllViewEnabled = true;
}
return policy;
}
/**
* Reload config from disk (for manual file edits or multi-instance).
*/
+60
View File
@@ -11,6 +11,7 @@ import {
import type { AdminConfigData, AdminStateData } from './types';
const MIGRATION_MARKER = '.migrated-v2';
const POLICY_UNIFIED_MARKER = '.migrated-unified-mailbox';
interface LegacyAdminData {
passwordHash: string;
@@ -59,6 +60,65 @@ export async function migrateLegacyAdminLayout(): Promise<void> {
}
}
/**
* One-shot policy migration for the Unified Mailbox rework. Before it, the
* cross views (crossUnread/crossStarred/crossAll) merged across every logged-in
* account, so an admin who had any of them enabled was already permitting
* cross-account aggregation. The new `unifiedCrossAccountEnabled` gate (default
* false) controls that capability, so enable it whenever a cross view was active
* - otherwise existing cross-account installs would silently lose the behaviour
* on upgrade (the per-user `unifiedCrossAccount` is AND-ed with this gate).
*
* Persisted + marker-guarded (not a per-load normalization) so a later admin
* decision to disable the gate survives restarts. Skipped on read-only config
* dirs - operators who locked their config must migrate manually (mirrors
* migrateLegacyAdminLayout). The deprecated `allMailViewEnabled` (a single-account
* view, never cross-account) deliberately does NOT trigger this.
*/
export async function migratePolicyUnifiedMailbox(): Promise<void> {
if (isConfigReadOnly()) return;
const markerPath = getConfigPath(POLICY_UNIFIED_MARKER);
if (existsSync(markerPath)) return;
try {
const policyPath = getConfigPath('policy.json');
if (existsSync(policyPath)) {
let parsed: Record<string, unknown> | null = null;
try {
parsed = JSON.parse(await readFile(policyPath, 'utf-8')) as Record<string, unknown>;
} catch {
logger.warn('policy.json is not valid JSON; skipping Unified Mailbox policy migration');
}
const features =
parsed && typeof parsed.features === 'object' && parsed.features
? (parsed.features as Record<string, unknown>)
: null;
if (features) {
const hadCrossAccount = !!(
features.crossUnreadViewEnabled ||
features.crossStarredViewEnabled ||
features.crossAllViewEnabled
);
if (hadCrossAccount && features.unifiedCrossAccountEnabled !== true) {
features.unifiedCrossAccountEnabled = true;
const tmp = policyPath + '.tmp';
await writeFile(tmp, JSON.stringify(parsed, null, 2), 'utf-8');
await rename(tmp, policyPath);
logger.info('Migrated policy: enabled unifiedCrossAccountEnabled (cross-account views were active)');
}
}
}
await ensureConfigDir();
await writeFile(markerPath, new Date().toISOString(), 'utf-8');
} catch (error) {
logger.warn('Unified Mailbox policy migration failed; will retry on next boot', {
error: error instanceof Error ? error.message : 'Unknown error',
});
}
}
/**
* If the existing admin.json carries timestamp fields (legacy mixed layout),
* split them into admin-state.json and rewrite admin.json without them.
+3
View File
@@ -60,10 +60,12 @@ export interface FeatureGates {
hoverActionsConfigEnabled: boolean;
filesEnabled: boolean;
contactsEnabled: boolean;
/** @deprecated Folded into `crossAllViewEnabled`; normalized forward on policy load. */
allMailViewEnabled: boolean;
crossUnreadViewEnabled: boolean;
crossStarredViewEnabled: boolean;
crossAllViewEnabled: boolean;
unifiedCrossAccountEnabled: boolean;
}
export const DEFAULT_FEATURE_GATES: FeatureGates = {
@@ -89,6 +91,7 @@ export const DEFAULT_FEATURE_GATES: FeatureGates = {
crossUnreadViewEnabled: false,
crossStarredViewEnabled: false,
crossAllViewEnabled: false,
unifiedCrossAccountEnabled: false,
};
export interface ThemePolicy {
+6 -13
View File
@@ -892,19 +892,12 @@ export function isUnifiedMailboxId(id: string): boolean {
}
/**
* Virtual mailbox id for the gated "All Mail" view: every folder of a single
* account merged into one date-sorted list. Distinct from the unified mailbox
* ids above, which merge one role across multiple accounts. Which folders are
* 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).
* Cross views shown in the unified ("Unified Mailbox") section: All mail /
* Unread / Starred. Each merges messages across the account boundary (the active
* account + its shared folders by default, or every logged-in account when the
* cross-account sub-option is on), narrowed by the user's folder selection (see
* `allMailFolderIds`). Distinct from the per-role unified ids (one role across
* accounts).
*/
export const CROSS_UNREAD = '__cross_unread__';
export const CROSS_STARRED = '__cross_starred__';
+22 -2
View File
@@ -22,6 +22,18 @@ export interface UnifiedAccountClient {
// must use the mailbox's `originalId` and explicitly target this accountId
// so the server routes to the owner's data.
isShared?: boolean;
// Store-side mailbox ids that make up THIS account's contribution to the
// cross views (All mail / Unread / Starred). It is intentionally per-account,
// not a global list: mailbox ids are account-scoped, so an id from one account
// is meaningless in another. The effective folder set of a cross view is the
// UNION across every account's entry (one UnifiedAccountClient per account),
// i.e. the sum of the respective per-account selections.
//
// For personal accounts this is the user's folder selection
// (`allMailFolderIds[accountId]`); shared/group accounts are not individually
// configurable and leave this undefined. When undefined, getCrossIncludedMailboxes
// falls back to the role-exclusion default (inbox + custom folders).
crossIncludedMailboxIds?: string[];
}
export interface UnifiedFetchResult {
@@ -313,10 +325,18 @@ export function fetchUnifiedMailboxCounts(
// 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).
* Mailboxes of an account included in the cross views (All mail / Unread /
* Starred). When the account carries an explicit `crossIncludedMailboxIds`
* selection (personal accounts honor the user's folder picker, shared accounts
* include everything), only those mailboxes are used. Otherwise it falls back
* to the role-exclusion default: everything whose role is not excluded (inbox +
* custom/no-role folders).
*/
export function getCrossIncludedMailboxes(account: UnifiedAccountClient): Mailbox[] {
if (account.crossIncludedMailboxIds) {
const selected = new Set(account.crossIncludedMailboxIds);
return account.mailboxes.filter((m) => selected.has(m.id));
}
return account.mailboxes.filter((m) => !CROSS_EXCLUDED_ROLES.has(m.role ?? ''));
}