{liveMessage &&
{liveMessage.text} }
diff --git a/components/mail/__tests__/blob-routing.test.tsx b/components/mail/__tests__/blob-routing.test.tsx
index 59b96c183..29c180bbb 100644
--- a/components/mail/__tests__/blob-routing.test.tsx
+++ b/components/mail/__tests__/blob-routing.test.tsx
@@ -800,6 +800,25 @@ function expectProBlob(route: typeof proRoutes[number], action: ProBlobAction, i
}
describe('Pro blob routing', () => {
+ it("opens a compose tab with the typed text for a notification's Reply, once, when the message is in", async () => {
+ const { requestTabReply } = await import('@/lib/pwa-notify/tab-reply');
+ const { useProTabStore } = await import('@/stores/pro-tab-store');
+ const { a } = await conversationClients();
+ vi.spyOn(a, 'getEmail').mockResolvedValue(message());
+ useEmailStore.setState({ emails: [], selectedEmail: null, isUnifiedView: false, selectedMailbox: 'inbox' });
+ useAuthStore.setState({ client: a, activeAccountId: 'login-primary' });
+ const composeTabs = () => useProTabStore.getState().tabs.filter((tab) => tab.kind === 'compose');
+ const before = composeTabs().length;
+
+ requestTabReply('email', 'Typed on the toast');
+ const view = render(
);
+ await waitFor(() => expect(composeTabs()).toHaveLength(before + 1));
+ expect(composeTabs().at(-1)?.composeData).toMatchObject({ mode: 'reply', sourceEmailId: 'email', initialDraftText: 'Typed on the toast' });
+
+ view.rerender(
);
+ expect(composeTabs()).toHaveLength(before + 1);
+ });
+
it.each(proRoutes.flatMap(route => proBlobActions.map(action => ({ ...route, action }))))(
'$label: $action uses the message owner and authenticated client', async route => {
const { origin, fetchMock } = await openProMessage(route, route.action);
diff --git a/components/mail/mail-app.tsx b/components/mail/mail-app.tsx
index 403114962..af75e3c96 100644
--- a/components/mail/mail-app.tsx
+++ b/components/mail/mail-app.tsx
@@ -142,6 +142,10 @@ import { usePluginStore } from "@/stores/plugin-store";
import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot";
import { canDownload } from "@/lib/device-policy";
import { consumePendingMailto, subscribeToPendingMailto } from "@/lib/protocol-handlers/session";
+import { setNotificationReplyOpener } from "@/lib/pwa-notify/page-actions";
+import { requestTabReply } from "@/lib/pwa-notify/tab-reply";
+import { consumePendingReplyText } from "@/lib/pwa-notify/worker-state";
+import { pendingHandoffs, subscribeHandoff, takeHandoff, type Handoff } from "@/lib/launch-handoff";
import { INTERNAL_MAILTO_EVENT, type ParsedMailto } from "@/lib/protocol-handlers/mailto";
import { PLUGIN_REPLY_EVENT, type PluginReplyRequest } from "@/lib/plugin-sandbox/host-api-compose";
import { onOpenEmail, type OpenEmailHandler, type OpenEmailOutcome } from "@/lib/plugin-sandbox/open-email";
@@ -173,7 +177,7 @@ import {
resolveFolderRef,
type MailDeepLink,
} from "@/lib/deep-links";
-import { consumePendingDeepLink, subscribePendingDeepLink } from "@/lib/deep-link-handoff";
+import { consumePendingDeepLinkEntry, subscribePendingDeepLink } from "@/lib/deep-link-handoff";
import { useProInterfaceActive } from "@/components/pro/pro-interface-redirect";
import type { QuoteHeader } from "@/lib/plugin-types";
import { initialLinkSearch, useLiteLinkSegments } from "@/hooks/use-lite-link-segments";
@@ -232,6 +236,9 @@ const UNIFIED_LIST_PUSH = {
},
};
+/** A draft from outside: a mailto:, or a share with files. ParsedMailto stays JSON, for sessionStorage. */
+type DraftRequest = ParsedMailto & { initialFiles?: File[]; unedited?: boolean };
+
export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// Static Lite build: the route params are empty, read the link from the URL.
const linkSegments = useLiteLinkSegments('mail', routeSegments);
@@ -259,6 +266,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
const [showComposer, setShowComposer] = useState(false);
const [composerMode, setComposerMode] = useState<'compose' | 'reply' | 'replyAll' | 'forward'>('compose');
const [composerDraftText, setComposerDraftText] = useState("");
+ // A notification's Reply, waiting for its message to be the open one.
+ const [pendingNotificationReply, setPendingNotificationReply] = useState<{ emailId: string; text: string } | null>(null);
const [pendingDraft, setPendingDraft] = useState
(null);
const [composerSessionId, setComposerSessionId] = useState(0);
// Fields a plugin filled in through onBeforeCompose for the composer about
@@ -316,7 +325,10 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// Office attachments open read-only in the configured WOPI editor (#1047).
const [officeAttachment, setOfficeAttachment] = useState<{ blobId: string; name: string; type?: string; size?: number; accountId: string; slot: number | null } | null>(null);
const wopiStatus = useWopiStatus(true);
- const [pendingMailtoAccountChoice, setPendingMailtoAccountChoice] = useState(null);
+ const [pendingMailtoAccountChoice, setPendingMailtoAccountChoice] = useState(null);
+ // Files from a share or a launch, for the next composer. It attaches an
+ // array once, so a stale one does nothing.
+ const [composerInitialFiles, setComposerInitialFiles] = useState(null);
const [isProtocolAccountSwitching, setIsProtocolAccountSwitching] = useState(false);
const markAsReadTimeoutRef = useRef(null);
const lastUndoToastSubmissionRef = useRef(null);
@@ -1378,6 +1390,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
initialDraftText: composerDraftText,
initialData: pendingDraft,
prefill: composerPrefill,
+ initialFiles: composerInitialFiles,
sourceEmailId: selectedEmail?.id ?? null,
sourceEmailSource: selectedEmail ? emailWriteSource(selectedEmail, client) : null,
title,
@@ -1388,6 +1401,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
setComposerDraftText("");
setPendingDraft(null);
setComposerPrefill(null);
+ setComposerInitialFiles(null);
setComposerQuoteHeader(null);
// We only react to the rising edge of `showComposer` here; the other
// variables read above are captured-but-stale-safe because the next
@@ -1467,18 +1481,22 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
return true;
}, [identities, t]);
- const applyMailtoDraft = useCallback((pending: ParsedMailto, suppressOutgoingStash: boolean) => {
+ const applyMailtoDraft = useCallback((pending: DraftRequest, suppressOutgoingStash: boolean) => {
if (suppressOutgoingStash) {
suppressComposerStateSaveSessionRef.current = composerSessionId;
}
setComposerSessionId((id) => id + 1);
- setPendingDraft(mailtoComposerDraft(pending, useSettingsStore.getState().plainTextMode));
+ setPendingDraft({
+ ...mailtoComposerDraft(pending, useSettingsStore.getState().plainTextMode),
+ ...(pending.unedited ? { unedited: true } : {}),
+ });
+ setComposerInitialFiles(pending.initialFiles ?? null);
setComposerMode("compose");
setShowComposer(true);
if (isMobile) setActiveView("viewer");
}, [composerSessionId, isMobile, setActiveView]);
- const openMailtoDraft = useCallback((pending: ParsedMailto) => withComposeGate('compose', {
+ const openMailtoDraft = useCallback((pending: DraftRequest) => withComposeGate('compose', {
to: pending.to, cc: pending.cc, subject: pending.subject, body: pending.body,
}, () => {
// A live composer owns text the user has not sent. Replacing it outright
@@ -1497,7 +1515,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
applyMailtoDraft(pending, showComposer);
}), [applyMailtoDraft, showComposer, withComposeGate]);
- const openMailtoForAccount = useCallback(async (pending: ParsedMailto, accountId: string) => {
+ const openMailtoForAccount = useCallback(async (pending: DraftRequest, accountId: string) => {
setIsProtocolAccountSwitching(true);
try {
if (useAuthStore.getState().activeAccountId !== accountId) {
@@ -1521,13 +1539,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
});
}, []);
- const handleMailtoProtocolRequest = useCallback(async (pending: ParsedMailto) => {
- if (!(await mailtoAllowed(pending))) return;
- // From another app of this webmail: the account in use, no question.
- if (pending.inApp) {
- openMailtoDraft(pending);
- return;
- }
+ // A draft that comes from outside: which account it goes out from.
+ const routeOutsideDraft = useCallback(async (pending: DraftRequest): Promise => {
const protocolAccounts = getMailtoProtocolAccounts();
if (protocolAccounts.length > 1) {
setPendingMailtoAccountChoice(pending);
@@ -1536,12 +1549,87 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
const accountId = protocolAccounts[0]?.id ?? activeAccountId;
if (accountId) {
- void openMailtoForAccount(pending, accountId);
+ await openMailtoForAccount(pending, accountId);
return;
}
- openMailtoDraft(pending);
- }, [activeAccountId, getMailtoProtocolAccounts, mailtoAllowed, openMailtoDraft, openMailtoForAccount]);
+ await openMailtoDraft(pending);
+ }, [activeAccountId, getMailtoProtocolAccounts, openMailtoDraft, openMailtoForAccount]);
+
+ const handleMailtoProtocolRequest = useCallback(async (pending: ParsedMailto) => {
+ if (!(await mailtoAllowed(pending))) return;
+ // From another app of this webmail: the account in use, no question.
+ if (pending.inApp) {
+ openMailtoDraft(pending);
+ return;
+ }
+ void routeOutsideDraft(pending);
+ }, [mailtoAllowed, openMailtoDraft, routeOutsideDraft]);
+
+ // A new draft from a shortcut, a share or the desktop app
+ // (lib/launch-handoff.ts). Not a mailto:, so onMailtoIntercept stays out of
+ // it; onBeforeCompose still runs. The standard page that renders while the
+ // Pro shell takes over must leave it for the Pro one.
+ const proTakingOver = proInterfaceActive && !isEmbedded;
+ // One at a time. A composer that is open holds the user's text, so what comes
+ // next stays queued until it closes, and a second one can't replace the
+ // first. So does one set aside by reading a message, while the server hasn't
+ // got what it holds. Under Pro a composer moves to its own tab, so nothing
+ // waits long.
+ const handoffOpeningRef = useRef(false);
+ const handoffToldWaitingRef = useRef(new Set());
+ const composerInUseRef = useRef(false);
+ const composerInUse = showComposer || pendingMailtoAccountChoice !== null
+ || pendingDraft?.unsaved === true || pendingDraft?.unedited === true;
+ composerInUseRef.current = composerInUse;
+ const [handoffSettled, setHandoffSettled] = useState(0);
+ useEffect(() => {
+ if (!isAuthenticated || !client || proTakingOver) return;
+
+ const open = async (handoff: Handoff) => {
+ if (!handoff.subject && !handoff.body && handoff.files.length === 0) {
+ await withComposeGate('compose', {}, () => {
+ startFreshComposerSession();
+ setComposerMode('compose');
+ setShowComposer(true);
+ if (isMobile) setActiveView('viewer');
+ });
+ return;
+ }
+ await routeOutsideDraft({
+ to: [],
+ cc: [],
+ bcc: [],
+ subject: handoff.subject ?? '',
+ body: handoff.body ?? '',
+ initialFiles: handoff.files,
+ unedited: true,
+ });
+ };
+
+ const openNext = () => {
+ if (handoffOpeningRef.current) return;
+ if (composerInUseRef.current) {
+ const waiting = pendingHandoffs().find((handoff) => handoff.kind === 'compose');
+ if (waiting && !handoffToldWaitingRef.current.has(waiting.id)) {
+ handoffToldWaitingRef.current.add(waiting.id);
+ toast.info(t('pwaLaunch.compose_waiting'));
+ }
+ return;
+ }
+ const handoff = takeHandoff('compose');
+ if (!handoff) return;
+ handoffOpeningRef.current = true;
+ void open(handoff).finally(() => {
+ handoffOpeningRef.current = false;
+ setHandoffSettled((n) => n + 1);
+ });
+ };
+
+ openNext();
+ return subscribeHandoff('compose', openNext);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isAuthenticated, client, proTakingOver, routeOutsideDraft, withComposeGate, isMobile, composerInUse, handoffSettled]);
useEffect(() => {
if (!isAuthenticated || !client) return;
@@ -1770,7 +1858,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
}
}
};
- const applyMailDeepLink = async (link: MailDeepLink, opts?: { onLoad?: boolean }) => {
+ const applyMailDeepLink = async (link: MailDeepLink, opts?: { onLoad?: boolean; replyText?: string }) => {
// The folder list before an account switch, if one happened: until the
// new mailbox's folders arrive the store still holds these (or nothing).
let switchedFrom: Mailbox[] | null = null;
@@ -1844,6 +1932,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// A shared account's message is fetched from that account through
// the active login (#1351).
const loginId = link.ownerAccountId ? useAuthStore.getState().activeAccountId ?? undefined : undefined;
+ // A notification's Reply: the tab opens its composer once it has the message.
+ if (link.reply) requestTabReply(link.id, opts?.replyText ?? await consumePendingReplyText(link.id));
useProTabStore.getState().openEmailTab({
accountId: link.ownerAccountId ?? '',
...(loginId ? { clientAccountId: loginId } : {}),
@@ -1869,6 +1959,12 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
}
if (isMobile) setActiveView('viewer');
if (isTablet) setTabletListVisible(false);
+ if (link.reply) {
+ // A notification's Reply. The branch above may have skipped
+ // selecting, and the reply has to wait for the message to be open.
+ selectEmail(email);
+ setPendingNotificationReply({ emailId: email.id, text: opts?.replyText ?? await consumePendingReplyText(email.id) });
+ }
} finally {
setLoadingEmail(false);
}
@@ -1923,8 +2019,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// briefly and must not steal the link parked for the Pro one.
useEffect(() => {
if (!isEmbedded) return;
- return subscribePendingDeepLink('mail', (segments) => {
- const link = parseMailPath(segments, new URLSearchParams(window.location.search));
+ return subscribePendingDeepLink('mail', (segments, search) => {
+ const link = parseMailPath(segments, new URLSearchParams(search ?? window.location.search));
if (link) void applyMailDeepLinkRef.current(link);
});
}, [isEmbedded]);
@@ -1975,10 +2071,13 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
}
if (!initialMailLoadDone) return;
+ // Inside the Pro shell the route is /pro, so the link arrives through the
+ // handoff the redirect parked it in rather than as route params. Its query
+ // comes with it: the address bar may have none left by the first render.
+ const parked = linkSegments ? null : consumePendingDeepLinkEntry('mail');
+ if (parked?.search) initialSearchRef.current = parked.search;
const params = new URLSearchParams(initialSearchRef.current ?? window.location.search);
- // Inside the Pro shell the route is /pro, so the segments arrive through
- // the handoff the redirect parked them in rather than as route params.
- const segments = linkSegments ?? consumePendingDeepLink('mail') ?? [];
+ const segments = linkSegments ?? parked?.segments ?? [];
const link = parseMailPath(segments, params);
const openLatestUnread = params.get('openLatestUnread') === '1';
@@ -2788,6 +2887,29 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
return () => window.removeEventListener(PLUGIN_REPLY_EVENT, onPluginReply);
}, []);
+ // A notification's Reply, from a `?reply=1` link or from the service worker
+ // when this tab is open. Both come through applyMailDeepLink and end here,
+ // once the message is the open one.
+ useEffect(() => {
+ if (!pendingNotificationReply || selectedEmail?.id !== pendingNotificationReply.emailId) return;
+ setPendingNotificationReply(null);
+ void pluginReplyRef.current.handleReply(pendingNotificationReply.text);
+ }, [pendingNotificationReply, selectedEmail?.id]);
+ const composerOpenRef = useRef(showComposer);
+ composerOpenRef.current = showComposer;
+ useEffect(() => {
+ return setNotificationReplyOpener(({ emailId, accountId, slot, text }) => {
+ const open = () => void applyMailDeepLinkRef.current(
+ { kind: 'message', id: emailId, slot, ownerAccountId: accountId, reply: true },
+ { replyText: text ?? '' },
+ );
+ // A live composer's text goes through its own "Save or discard?" first.
+ const requestClose = composerRequestCloseRef.current;
+ if (composerOpenRef.current && requestClose) requestClose(open);
+ else open();
+ });
+ }, []);
+
// A plugin opening a message (api.ui.openEmail), as a click on a search
// result entry naming one does: handleEmailSelect, set once it is defined.
// Not inside the Pro shell, which keeps this tab mounted while hidden and
@@ -4872,6 +4994,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
initialDraftText={composerDraftText}
initialData={pendingDraft}
prefill={composerPrefill}
+ initialFiles={composerInitialFiles}
sessionKey={`inline-${composerSessionId}`}
sourceEmailId={composerSourceEmail?.id}
onSaveState={(data) => {
diff --git a/components/pro/pro-compose-tab-body.tsx b/components/pro/pro-compose-tab-body.tsx
index 3094fa0ff..0f055e027 100644
--- a/components/pro/pro-compose-tab-body.tsx
+++ b/components/pro/pro-compose-tab-body.tsx
@@ -264,6 +264,7 @@ export function ProComposeTabBody({ tabId, data }: ProComposeTabBodyProps) {
initialDraftText={data.initialDraftText}
initialData={data.initialData}
prefill={data.prefill}
+ initialFiles={data.initialFiles}
sessionKey={`pro-${tabId}-${data.sessionId}`}
sourceEmailId={data.sourceEmailId ?? undefined}
composeFromAccountEmail={composeFromAccountEmail}
diff --git a/components/pro/pro-email-tab-body.tsx b/components/pro/pro-email-tab-body.tsx
index 224951911..e5056670a 100644
--- a/components/pro/pro-email-tab-body.tsx
+++ b/components/pro/pro-email-tab-body.tsx
@@ -28,6 +28,7 @@ import { labelSourceHeaders, reopenedLabelChoice } from '@/lib/outgoing/classifi
import { useArchiveActionEnabled } from '@/lib/archive-gate';
import { confirmMailRemoval } from '@/lib/mail-removal-confirm';
import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
+import { takeTabReply, useNotificationTabReply } from '@/lib/pwa-notify/tab-reply';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { saveQuickReplyDraft } from '@/lib/outgoing/quick-reply-envelope';
import { canDownload } from '@/lib/device-policy';
@@ -283,6 +284,14 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
}, { source: email, body: draftText ?? '' });
}, [email, openComposeTab, t, writeSource]);
+ // A notification's Reply, once this tab has the message (mail-app.tsx).
+ const pendingTabReply = useNotificationTabReply((s) => s.pending);
+ useEffect(() => {
+ if (!email || pendingTabReply?.emailId !== email.id) return;
+ const text = takeTabReply(email.id);
+ if (text !== null) handleReply(text);
+ }, [email, pendingTabReply, handleReply]);
+
const handleReplyAll = useCallback(() => {
if (!email) return;
openComposeTab({
diff --git a/components/protocol/__tests__/protocol-launch-handler-provider.test.tsx b/components/protocol/__tests__/protocol-launch-handler-provider.test.tsx
new file mode 100644
index 000000000..15ffa7cf2
--- /dev/null
+++ b/components/protocol/__tests__/protocol-launch-handler-provider.test.tsx
@@ -0,0 +1,430 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import React from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { FakeCaches } from '@/lib/__tests__/sw-harness';
+
+// The launchQueue consumer. It is the only one the app may have: a second
+// setConsumer replaces the first. Files used to be dropped here.
+
+const hoisted = vi.hoisted(() => ({
+ push: vi.fn(),
+ pathname: { current: '/' },
+ toastError: vi.fn(),
+ toastInfo: vi.fn(),
+ flushComposers: vi.fn(async () => ({ total: 0, settled: 0, failed: 0, timedOut: false })),
+ peek: vi.fn(),
+ adopt: vi.fn(),
+ discard: vi.fn(async () => {}),
+ savePendingMailto: vi.fn(),
+ protocolOpenMode: 'active-session',
+}));
+
+vi.mock('@/i18n/navigation', () => ({
+ useRouter: () => ({ push: hoisted.push, replace: vi.fn(), back: vi.fn() }),
+ usePathname: () => hoisted.pathname.current,
+}));
+vi.mock('@/hooks/use-config', () => ({ useConfig: () => ({ appName: 'Bulwark' }) }));
+vi.mock('@/stores/toast-store', () => ({ toast: { error: hoisted.toastError, info: hoisted.toastInfo, success: vi.fn() } }));
+vi.mock('@/lib/compose-flush-registry', () => ({ flushComposers: hoisted.flushComposers }));
+vi.mock('@/lib/launch-handoff', async (importOriginal) => ({
+ ...(await importOriginal()),
+ peekStoredHandoff: hoisted.peek,
+ adoptStoredHandoff: hoisted.adopt,
+ discardStoredHandoff: hoisted.discard,
+}));
+vi.mock('@/stores/settings-store', () => ({
+ useSettingsStore: Object.assign(() => undefined, { getState: () => ({ protocolOpenMode: hoisted.protocolOpenMode }) }),
+}));
+vi.mock('@/lib/protocol-handlers/session', () => ({
+ listenForMailtoRequests: () => () => {},
+ notifyPendingMailto: vi.fn(),
+ notifyPendingWebcal: vi.fn(),
+ requestOpenMailtoInExistingClient: vi.fn(async () => false),
+ savePendingMailto: hoisted.savePendingMailto,
+ savePendingWebcal: vi.fn(),
+}));
+// The real modal has its own tests; here: does the launch reach it, and is
+// its download gated by the same function.
+vi.mock('@/components/files/file-preview-modal', () => ({
+ FilePreviewModal: function PreviewStub({ name, onClose, onDownload, getFileContent }: {
+ name: string; onClose: () => void; onDownload: () => void;
+ getFileContent: () => Promise<{ blob: Blob; contentType: string }>;
+ }) {
+ const [type, setType] = React.useState('');
+ React.useEffect(() => { void getFileContent().then((c) => setType(c.contentType)); }, [getFileContent]);
+ return (
+
+ {name}
+ close
+ save
+
+ );
+ },
+}));
+
+const { clearHandoffs, handOffFiles, pendingHandoffs, takeHandoff, HANDOFF_TTL_MS } = await import('@/lib/launch-handoff');
+const { setDownloadGuard } = await import('@/lib/download-guard');
+const { ProtocolLaunchHandlerProvider } = await import('../protocol-launch-handler-provider');
+
+type Consumer = (params: { targetURL?: string; files?: Array<{ kind: string; getFile: () => Promise }> }) => void;
+
+let consumer: Consumer | null = null;
+const setConsumer = vi.fn((fn: Consumer) => { consumer = fn; });
+const handle = (name: string, type = '') => ({ kind: 'file', getFile: async () => new File(['x'], name, { type }) });
+const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); });
+
+function mount() {
+ return render(app
);
+}
+
+beforeEach(() => {
+ consumer = null;
+ setConsumer.mockClear();
+ hoisted.push.mockClear();
+ hoisted.toastError.mockClear();
+ hoisted.toastInfo.mockClear();
+ hoisted.flushComposers.mockReset();
+ hoisted.flushComposers.mockResolvedValue({ total: 0, settled: 0, failed: 0, timedOut: false });
+ hoisted.peek.mockReset();
+ hoisted.adopt.mockReset();
+ hoisted.discard.mockClear();
+ hoisted.savePendingMailto.mockClear();
+ hoisted.pathname.current = '/';
+ hoisted.protocolOpenMode = 'active-session';
+ sessionStorage.clear();
+ vi.stubGlobal('caches', new FakeCaches());
+ window.launchQueue = { setConsumer } as never;
+});
+
+afterEach(() => {
+ clearHandoffs();
+ delete window.launchQueue;
+ vi.unstubAllGlobals();
+ window.history.replaceState(null, '', '/');
+});
+
+describe('file launches', () => {
+ it('opens a .eml in the viewer without leaving the page', async () => {
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/mail`, files: [handle('note.eml')] });
+ const viewer = await screen.findByTestId('eml-viewer');
+ expect(viewer).toHaveTextContent('note.eml');
+ await waitFor(() => expect(viewer).toHaveAttribute('data-type', 'message/rfc822'));
+ expect(hoisted.push).not.toHaveBeenCalled();
+ });
+
+ it('shows several .eml files one after the other', async () => {
+ mount();
+ consumer!({ files: [handle('one.eml'), handle('two.eml')] });
+ expect(await screen.findByTestId('eml-viewer')).toHaveTextContent('one.eml');
+ await act(async () => { screen.getByText('close').click(); });
+ expect(await screen.findByTestId('eml-viewer')).toHaveTextContent('two.eml');
+ await act(async () => { screen.getByText('close').click(); });
+ expect(screen.queryByTestId('eml-viewer')).toBeNull();
+ });
+
+ it("saves a .eml only if the device policy allows downloads", async () => {
+ const created = vi.fn(() => 'blob:x');
+ vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: created, revokeObjectURL: vi.fn() }));
+ setDownloadGuard(() => false);
+ mount();
+ consumer!({ files: [handle('note.eml')] });
+ await screen.findByTestId('eml-viewer');
+ await act(async () => { screen.getByText('save').click(); });
+ expect(created).not.toHaveBeenCalled();
+ setDownloadGuard(null);
+ });
+
+ it('takes a .ics to the calendar with the file waiting', async () => {
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/calendar`, files: [handle('invite.ics')] });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledWith('/calendar');
+ expect(takeHandoff('calendar')?.files[0].name).toBe('invite.ics');
+ });
+
+ it('takes a .vcf to the contacts with the file waiting', async () => {
+ mount();
+ consumer!({ files: [handle('people.vcf')] });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledWith('/contacts');
+ expect(takeHandoff('contacts')?.files[0].name).toBe('people.vcf');
+ });
+
+ it('stays when already on the right page', async () => {
+ hoisted.pathname.current = '/calendar';
+ mount();
+ consumer!({ files: [handle('invite.ics')] });
+ await flush();
+ expect(hoisted.push).not.toHaveBeenCalled();
+ });
+
+ it('goes to the page in the Pro shell too, which has one route', async () => {
+ hoisted.pathname.current = '/pro';
+ mount();
+ consumer!({ files: [handle('invite.ics')] });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledWith('/calendar');
+ });
+
+ it('says so for a file it cannot handle', async () => {
+ mount();
+ consumer!({ files: [handle('photo.png', 'image/png')] });
+ await flush();
+ expect(hoisted.toastError).toHaveBeenCalledWith('unsupported_file');
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('says so for a file it cannot read', async () => {
+ mount();
+ consumer!({ files: [{ kind: 'file', getFile: async () => { throw new Error('denied'); } }] });
+ await flush();
+ expect(hoisted.toastError).toHaveBeenCalledWith('open_failed');
+ });
+
+ it('waits on the sign-in page, and goes on after it', async () => {
+ hoisted.pathname.current = '/login';
+ const view = mount();
+ consumer!({ files: [handle('invite.ics')] });
+ await flush();
+ expect(hoisted.push).not.toHaveBeenCalled();
+
+ hoisted.pathname.current = '/';
+ view.rerender(app
);
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledTimes(1);
+ expect(hoisted.push).toHaveBeenCalledWith('/calendar');
+ });
+
+ it('goes to the page only once for a handoff, so it does not trap a later visit elsewhere', async () => {
+ hoisted.pathname.current = '/settings';
+ const view = mount();
+ consumer!({ files: [handle('invite.ics')] });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledTimes(1);
+
+ hoisted.pathname.current = '/mail';
+ view.rerender(app
);
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('launches that are not files', () => {
+ it('still handles mailto:', async () => {
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/protocol/mailto?url=${encodeURIComponent('mailto:a@example.org')}` });
+ await waitFor(() => expect(hoisted.savePendingMailto).toHaveBeenCalled());
+ expect(hoisted.savePendingMailto.mock.calls[0][0].to).toEqual(['a@example.org']);
+ });
+
+ it('opens a new message from the shortcut in an open window', async () => {
+ hoisted.pathname.current = '/settings';
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/?compose=1` });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledWith('/');
+ expect(takeHandoff('compose')).toMatchObject({ files: [] });
+ });
+
+ it('goes to the calendar from its shortcut in an open window', async () => {
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/calendar` });
+ await flush();
+ expect(hoisted.push).toHaveBeenCalledWith('/calendar');
+ });
+
+ it('leaves an open window where it is for the plain app icon', async () => {
+ hoisted.pathname.current = '/settings';
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/` });
+ await flush();
+ expect(hoisted.push).not.toHaveBeenCalled();
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('ignores a launch of the share target: the service worker has that', async () => {
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/protocol/share` });
+ await flush();
+ expect(hoisted.push).not.toHaveBeenCalled();
+ expect(hoisted.toastError).not.toHaveBeenCalled();
+ });
+
+ it('asks launchQueue once per consumer: never a second one on one render', () => {
+ mount();
+ expect(setConsumer).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('leaving a composer for a launched file', () => {
+ it('saves what was typed first, then goes', async () => {
+ const order: string[] = [];
+ hoisted.flushComposers.mockImplementation(async () => { order.push('flush'); return { total: 1, settled: 1, failed: 0, timedOut: false }; });
+ hoisted.push.mockImplementation(() => { order.push('push'); });
+ mount();
+ consumer!({ files: [handle('people.vcf')] });
+ await flush();
+ expect(order).toEqual(['flush', 'push']);
+ hoisted.push.mockReset();
+ });
+
+ it.each([
+ ['the server refused the save', { total: 1, settled: 1, failed: 1, timedOut: false }],
+ ['the save took too long', { total: 1, settled: 0, failed: 0, timedOut: true }],
+ ])('stays when %s, with the file still waiting', async (_name, result) => {
+ hoisted.flushComposers.mockResolvedValue(result);
+ mount();
+ consumer!({ files: [handle('people.vcf')] });
+ await flush();
+ expect(hoisted.push).not.toHaveBeenCalled();
+ expect(hoisted.toastError).toHaveBeenCalledWith('save_first_failed');
+ expect(pendingHandoffs().map((h) => h.kind)).toEqual(['contacts']);
+ });
+
+ it('does not save for a .eml, which leaves nothing', async () => {
+ mount();
+ consumer!({ files: [handle('note.eml')] });
+ await screen.findByTestId('eml-viewer');
+ expect(hoisted.flushComposers).not.toHaveBeenCalled();
+ });
+});
+
+describe('a handoff that goes without arriving', () => {
+ it('says so', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ mount();
+ handOffFiles([new File(['x'], 'a.ics')], 'calendar');
+ vi.advanceTimersByTime(HANDOFF_TTL_MS + 1);
+ takeHandoff('calendar');
+ vi.useRealTimers();
+ expect(hoisted.toastError).toHaveBeenCalledWith('handoff_expired');
+ });
+});
+
+describe('the address a launch lands on', () => {
+ it('opens a new message once and removes the parameter', async () => {
+ window.history.replaceState(null, '', '/?compose=1&slot=2#x');
+ mount();
+ expect(window.location.search).toBe('?slot=2');
+ expect(window.location.hash).toBe('#x');
+ expect(takeHandoff('compose')).toMatchObject({ files: [] });
+ expect(takeHandoff('compose')).toBeNull();
+ });
+
+ it('counts the same launch once when launchQueue names it too', async () => {
+ window.history.replaceState(null, '', '/?compose=1');
+ mount();
+ consumer!({ targetURL: `${window.location.origin}/?compose=1` });
+ await flush();
+ expect(takeHandoff('compose')).not.toBeNull();
+ expect(takeHandoff('compose')).toBeNull();
+ });
+});
+
+describe('a share from an address anyone can make', () => {
+ const dialogText = () => screen.getByTestId('share-confirm-details').textContent ?? '';
+ const agree = () => fireEvent.click(screen.getByRole('button', { name: 'share_confirm_accept' }));
+ const refuse = () => fireEvent.click(screen.getByRole('button', { name: 'share_confirm_decline' }));
+
+ it('asks about text in the address, and starts nothing before the answer', async () => {
+ window.history.replaceState(null, '', '/#share=unavailable&share_title=T&share_text=B&share_files=1&share_cut=1');
+ mount();
+ expect(window.location.hash).toBe('');
+ await screen.findByText('share_confirm_message');
+ expect(dialogText()).toContain('T');
+ expect(pendingHandoffs()).toEqual([]);
+ expect(hoisted.push).not.toHaveBeenCalled();
+
+ agree();
+ await flush();
+ expect(takeHandoff('compose')).toMatchObject({ subject: 'T', body: 'B' });
+ expect(hoisted.toastError).toHaveBeenCalledWith('share_files_lost');
+ expect(hoisted.toastInfo).toHaveBeenCalledWith('share_cut');
+ });
+
+ it('starts nothing when refused', async () => {
+ window.history.replaceState(null, '', '/#share=unavailable&share_text=B');
+ mount();
+ await screen.findByText('share_confirm_message');
+ refuse();
+ await flush();
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('only reports lost files when there was no text to ask about', async () => {
+ window.history.replaceState(null, '', '/#share=unavailable&share_files=1');
+ mount();
+ await flush();
+ expect(screen.queryByText('share_confirm_message')).toBeNull();
+ expect(hoisted.toastError).toHaveBeenCalledWith('share_files_lost');
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('ignores it in the query, which reaches logs and any link', async () => {
+ window.history.replaceState(null, '', '/?share=unavailable&share_text=B');
+ mount();
+ await flush();
+ expect(screen.queryByText('share_confirm_message')).toBeNull();
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('asks about a stored share, naming the files, before anything is taken in', async () => {
+ hoisted.peek.mockResolvedValue({ subject: 'S', body: '', files: ['invoice.exe'] });
+ hoisted.adopt.mockResolvedValue(true);
+ window.history.replaceState(null, '', '/#share=abc&key=k1');
+ mount();
+ expect(window.location.hash).toBe('');
+ await screen.findByText('share_confirm_message');
+ expect(hoisted.peek).toHaveBeenCalledWith('abc', 'k1');
+ expect(dialogText()).toContain('invoice.exe');
+ expect(hoisted.adopt).not.toHaveBeenCalledWith('abc', 'k1');
+
+ agree();
+ await waitFor(() => expect(hoisted.adopt).toHaveBeenCalledWith('abc', 'k1'));
+ expect(hoisted.discard).not.toHaveBeenCalled();
+ });
+
+ it('asks in an installed-app window as well: link capturing can bring a POST there', async () => {
+ const original = window.matchMedia;
+ window.matchMedia = ((query: string) => ({ matches: query.includes('standalone'), media: query, addEventListener: () => {}, removeEventListener: () => {} })) as never;
+ hoisted.peek.mockResolvedValue({ subject: 'S', body: '', files: [] });
+ window.history.replaceState(null, '', '/#share=abc&key=k1');
+ mount();
+ await screen.findByText('share_confirm_message');
+ expect(hoisted.adopt).not.toHaveBeenCalledWith('abc', 'k1');
+ window.matchMedia = original;
+ });
+
+ it('drops a stored share when refused', async () => {
+ hoisted.peek.mockResolvedValue({ subject: 'S', body: '', files: ['invoice.exe'] });
+ window.history.replaceState(null, '', '/#share=abc&key=k1');
+ mount();
+ await screen.findByText('share_confirm_message');
+ refuse();
+ await waitFor(() => expect(hoisted.discard).toHaveBeenCalledWith('abc'));
+ expect(hoisted.adopt).not.toHaveBeenCalledWith('abc', 'k1');
+ });
+
+ it('says so when what was shared is gone', async () => {
+ hoisted.peek.mockResolvedValue(null);
+ window.history.replaceState(null, '', '/#share=abc&key=k1');
+ mount();
+ expect(window.location.hash).toBe('');
+ await flush();
+ expect(hoisted.toastError).toHaveBeenCalledWith('share_gone');
+ expect(screen.queryByText('share_confirm_message')).toBeNull();
+ });
+});
+
+describe('a browser without launchQueue', () => {
+ it('renders the app and does nothing else', async () => {
+ delete window.launchQueue;
+ mount();
+ await flush();
+ expect(screen.getByText('app')).toBeInTheDocument();
+ expect(setConsumer).not.toHaveBeenCalled();
+ expect(hoisted.push).not.toHaveBeenCalled();
+ expect(pendingHandoffs()).toEqual([]);
+ });
+});
diff --git a/components/protocol/launch-file-host.tsx b/components/protocol/launch-file-host.tsx
new file mode 100644
index 000000000..4c18d2fd5
--- /dev/null
+++ b/components/protocol/launch-file-host.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { useCallback, useEffect, useState, type ComponentType, type ComponentProps } from "react";
+import { useTranslations } from "next-intl";
+import type { FilePreviewModal as FilePreviewModalType } from "@/components/files/file-preview-modal";
+import { useHandoffFiles } from "@/hooks/use-handoff-files";
+import { saveBlobAs } from "@/lib/download-guard";
+import { toast } from "@/stores/toast-store";
+
+type PreviewComponent = ComponentType>;
+
+/**
+ * Shows a .eml opened from the OS. It parses in the browser, so it works
+ * offline and before sign-in. `policyAccount` stays out: the strictest device
+ * policy of the accounts signed in here decides about saving (FilePreviewModal
+ * and saveBlobAs check it).
+ *
+ * The preview is loaded when a file arrives, to keep it off the layout's
+ * bundle, and by hand rather than with next/dynamic: without a connection and
+ * without the offline shell its chunk can't load, which has to end in a
+ * message, not in the error page, and work again later.
+ */
+export function LaunchFileHost() {
+ const t = useTranslations("pwaLaunch");
+ const { file, done } = useHandoffFiles("eml", true);
+ const [Preview, setPreview] = useState(null);
+
+ useEffect(() => {
+ if (!file || Preview) return;
+ let stale = false;
+ import("@/components/files/file-preview-modal")
+ .then((module) => {
+ if (!stale) setPreview(() => module.FilePreviewModal);
+ })
+ .catch(() => {
+ if (stale) return;
+ toast.error(t("open_failed"));
+ done();
+ });
+ return () => { stale = true; };
+ }, [file, Preview, done, t]);
+
+ const getFileContent = useCallback(async () => {
+ if (!file) throw new Error("no file");
+ return { blob: file, contentType: "message/rfc822" };
+ }, [file]);
+
+ const onDownload = useCallback(() => {
+ if (file) saveBlobAs(file, file.name, { kind: "attachment" });
+ }, [file]);
+
+ if (!file || !Preview) return null;
+ return (
+
+ );
+}
diff --git a/components/protocol/protocol-launch-handler-provider.tsx b/components/protocol/protocol-launch-handler-provider.tsx
index dbf35ed56..3cab2f174 100644
--- a/components/protocol/protocol-launch-handler-provider.tsx
+++ b/components/protocol/protocol-launch-handler-provider.tsx
@@ -1,12 +1,32 @@
"use client";
-import { useEffect } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useTranslations } from "next-intl";
import { usePathname, useRouter } from "@/i18n/navigation";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useConfig } from "@/hooks/use-config";
+import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
+import { flushComposers } from "@/lib/compose-flush-registry";
import { isPopoutPath } from "@/lib/popout/window-role";
import { getPathPrefix } from "@/lib/browser-navigation";
+import { matchSurface, type AppSurface } from "@/lib/deep-links";
+import {
+ adoptStoredHandoff,
+ discardStoredHandoff,
+ handOffDraft,
+ handOffLaunchFiles,
+ handOffNewMessage,
+ parseLaunchLanding,
+ peekStoredHandoff,
+ pendingHandoffs,
+ restoreStoredHandoffs,
+ shortcutFromTargetUrl,
+ stripLandingParams,
+ subscribeHandoff,
+ subscribeHandoffLost,
+ type HandoffKind,
+} from "@/lib/launch-handoff";
import { productName } from "@/lib/product-name";
import { parseMailto } from "@/lib/protocol-handlers/mailto";
import { parseWebcal } from "@/lib/protocol-handlers/webcal";
@@ -19,8 +39,13 @@ import {
savePendingWebcal,
} from "@/lib/protocol-handlers/session";
import { useSettingsStore } from "@/stores/settings-store";
+import { toast } from "@/stores/toast-store";
+import { LaunchFileHost } from "./launch-file-host";
-type LaunchParams = { targetURL?: string };
+type LaunchParams = {
+ targetURL?: string;
+ files?: ReadonlyArray<{ kind?: string; getFile?: () => Promise }>;
+};
type StandaloneNavigator = Navigator & { standalone?: boolean };
declare global {
@@ -52,6 +77,21 @@ function getProtocolLaunch(targetURL: string):
return null;
}
+/** The page a handoff waits for. A .eml has none: it opens over any page. */
+const HANDOFF_TARGET: Partial> = {
+ compose: { surface: "mail", path: "/" },
+ calendar: { surface: "calendar", path: "/calendar" },
+ contacts: { surface: "contacts", path: "/contacts" },
+};
+
+/** How long a launch waits for an open composer to save before it leaves the page. */
+const FLUSH_BEFORE_LEAVING_MS = 5000;
+/** How much of a share the question shows. */
+const OFFER_TEXT_LENGTH = 200;
+const OFFER_FILE_COUNT = 5;
+
+type ShareOffer = { subject: string; body: string; files: string[] };
+
function isStandaloneDisplayMode() {
return window.matchMedia?.("(display-mode: standalone)").matches
|| (navigator as StandaloneNavigator).standalone === true;
@@ -74,6 +114,97 @@ export function ProtocolLaunchHandlerProvider({ children }: ProtocolLaunchHandle
const appName = productName(useConfig().appName);
const router = useRouter();
const pathname = usePathname();
+ const tLaunch = useTranslations("pwaLaunch");
+ const sentToTarget = useRef(new Set());
+ const { dialogProps, confirm } = useConfirmDialog();
+ const [offer, setOffer] = useState(null);
+
+ // Anyone can POST to the share target or link to a landing address, and
+ // Chromium's link capturing can bring a cross-site form POST into an
+ // installed app's window, so nothing tells a real share from a planted one.
+ // Nothing goes into an account until the user says yes.
+ const askAboutShare = useCallback(async (shared: ShareOffer) => {
+ setOffer(shared);
+ const agreed = await confirm({
+ title: tLaunch("share_confirm_title"),
+ message: tLaunch("share_confirm_message"),
+ confirmText: tLaunch("share_confirm_accept"),
+ cancelText: tLaunch("share_confirm_decline"),
+ });
+ setOffer(null);
+ return agreed;
+ }, [confirm, tLaunch]);
+
+ // What the page's own address asks for: a shortcut's new message, or what
+ // was shared. Once: it leaves the address before anything else happens.
+ useEffect(() => {
+ const stopLossNotes = subscribeHandoffLost((loss) => {
+ toast.error(tLaunch(loss === "missing" ? "share_files_lost" : "handoff_expired"));
+ });
+ const { search, hash, pathname: path } = window.location;
+ const landing = parseLaunchLanding(search, hash);
+ if (landing) {
+ const left = stripLandingParams(search, hash);
+ window.history.replaceState(window.history.state, "", path + left.search + left.hash);
+ }
+ if (landing?.type === "new-message") {
+ handOffNewMessage();
+ } else if (landing?.type === "inline") {
+ void (async () => {
+ const { subject, body } = landing;
+ if ((subject || body) && !(await askAboutShare({ subject, body, files: [] }))) return;
+ if (subject || body) handOffDraft({ subject, body });
+ if (landing.filesLost) toast.error(tLaunch("share_files_lost"));
+ if (landing.cut) toast.info(tLaunch("share_cut"));
+ })();
+ } else if (landing?.type === "stored") {
+ void (async () => {
+ const shared = await peekStoredHandoff(landing.id, landing.key);
+ if (!shared) {
+ await discardStoredHandoff(landing.id);
+ toast.error(tLaunch("share_gone"));
+ return;
+ }
+ if (!(await askAboutShare(shared))) {
+ await discardStoredHandoff(landing.id);
+ return;
+ }
+ if (!(await adoptStoredHandoff(landing.id, landing.key))) toast.error(tLaunch("share_gone"));
+ })();
+ }
+ void restoreStoredHandoffs();
+ return stopLossNotes;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Leaving the mail page ends an open composer, and its autosave waits 2
+ // seconds: what was just typed is saved first. If it can't be, stay. A file
+ // keeps waiting and opens once the user goes to that page.
+ const leaveFor = useCallback(async (path: "/" | "/calendar" | "/contacts") => {
+ const result = await flushComposers(FLUSH_BEFORE_LEAVING_MS);
+ if (result.failed > 0 || result.timedOut) {
+ toast.error(tLaunch("save_first_failed"));
+ return;
+ }
+ router.push(path);
+ }, [router, tLaunch]);
+
+ // Takes a handoff to the page that handles it, once each: on arrival, or
+ // when the sign-in it had to wait for is done.
+ useEffect(() => {
+ const goToTarget = () => {
+ if (pathname === "/login" || pathname.startsWith("/login/") || pathname.startsWith("/auth/")) return;
+ for (const handoff of pendingHandoffs()) {
+ const target = HANDOFF_TARGET[handoff.kind];
+ if (!target || sentToTarget.current.has(handoff.id)) continue;
+ sentToTarget.current.add(handoff.id);
+ if (matchSurface(pathname)?.surface !== target.surface) void leaveFor(target.path as "/" | "/calendar" | "/contacts");
+ return;
+ }
+ };
+ goToTarget();
+ return subscribeHandoff("any", goToTarget);
+ }, [pathname, leaveFor]);
useEffect(() => {
if (pathname.startsWith("/protocol/") || isPopoutPath(pathname)) return;
@@ -94,10 +225,23 @@ export function ProtocolLaunchHandlerProvider({ children }: ProtocolLaunchHandle
if (typeof window === "undefined" || !window.launchQueue || isPopoutPath(pathname)) return;
window.launchQueue.setConsumer((launchParams) => {
+ if (launchParams.files && launchParams.files.length > 0) {
+ void handOffLaunchFiles(launchParams.files).then(({ unsupported, failed }) => {
+ for (const name of unsupported) toast.error(tLaunch("unsupported_file", { name }));
+ if (failed > 0) toast.error(tLaunch("open_failed"));
+ });
+ return;
+ }
+
if (!launchParams.targetURL) return;
const launch = getProtocolLaunch(launchParams.targetURL);
- if (!launch) return;
+ if (!launch) {
+ const shortcut = shortcutFromTargetUrl(launchParams.targetURL, window.location.origin);
+ if (shortcut === "new-message") handOffNewMessage();
+ else if (shortcut && matchSurface(pathname)?.surface !== shortcut) void leaveFor(`/${shortcut}`);
+ return;
+ }
if (launch.kind === "mailto") {
const parsed = parseMailto(launch.raw);
@@ -131,7 +275,23 @@ export function ProtocolLaunchHandlerProvider({ children }: ProtocolLaunchHandle
notifyPendingWebcal();
if (pathname !== "/calendar") router.push("/calendar");
});
- }, [pathname, router]);
+ }, [pathname, router, tLaunch, leaveFor]);
- return children;
+ const offeredFiles = offer?.files ?? [];
+ return (
+ <>
+ {children}
+
+
+ {offer.subject &&
{tLaunch("share_confirm_subject")} {offer.subject} }
+ {offer.body &&
{tLaunch("share_confirm_text")} {offer.body.slice(0, OFFER_TEXT_LENGTH)} }
+ {offeredFiles.length > 0 &&
{tLaunch("share_confirm_files", { count: offeredFiles.length })} {offeredFiles.slice(0, OFFER_FILE_COUNT).join(", ")}{offeredFiles.length > OFFER_FILE_COUNT ? ", …" : ""} }
+
+ )}
+ />
+ >
+ );
}
diff --git a/components/providers/__tests__/notification-actions-host.test.tsx b/components/providers/__tests__/notification-actions-host.test.tsx
new file mode 100644
index 000000000..f786d3e39
--- /dev/null
+++ b/components/providers/__tests__/notification-actions-host.test.tsx
@@ -0,0 +1,170 @@
+import { act, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { loginFingerprint } from '@/lib/pwa-notify/login-fingerprint';
+import { NotificationActionsHost } from '../notification-actions-host';
+
+// The tab's end of the service worker: it keeps the worker's copy of the
+// labels and archive settings, runs notification buttons and flushes the
+// outbox when the worker says so.
+
+const writeNotificationActionPrefs = vi.fn(async (..._args: unknown[]) => {});
+const runNotificationAction = vi.fn(async (_request: unknown, answer: (status: string) => void) => answer('done'));
+const scheduleFlushAll = vi.fn();
+let state = { isAuthenticated: true, archiveMode: 'month', archiveEnabled: true, plugins: [] as Array>, accounts: [] as Array<{ serverUrl: string; username: string }> };
+
+vi.mock('@/lib/pwa-notify/worker-state', () => ({
+ writeNotificationActionPrefs: (...args: unknown[]) => writeNotificationActionPrefs(...args),
+}));
+vi.mock('@/lib/pwa-notify/page-actions', async () => {
+ const actual = await vi.importActual('@/lib/pwa-notify/page-actions');
+ return { isNotificationActionRequest: actual.isNotificationActionRequest, runNotificationAction: (...args: Parameters) => runNotificationAction(...args) };
+});
+vi.mock('@/lib/offline/offline-mode', () => ({ scheduleFlushAll: (...args: unknown[]) => scheduleFlushAll(...args) }));
+vi.mock('@/lib/archive-gate', () => ({ useArchiveActionEnabled: () => state.archiveEnabled }));
+vi.mock('@/stores/auth-store', () => ({
+ useAuthStore: (select: (s: { isAuthenticated: boolean }) => unknown) => select({ isAuthenticated: state.isAuthenticated }),
+}));
+vi.mock('@/stores/settings-store', () => ({
+ useSettingsStore: (select: (s: { archiveMode: string }) => unknown) => select({ archiveMode: state.archiveMode }),
+}));
+vi.mock('@/stores/plugin-store', () => ({
+ usePluginStore: (select: (s: { plugins: unknown[] }) => unknown) => select({ plugins: state.plugins }),
+}));
+vi.mock('@/stores/email-store', () => ({ useEmailStore: { getState: () => ({}) } }));
+vi.mock('@/stores/account-store', () => {
+ const useAccountStore = (select: (s: { accounts: unknown[] }) => unknown) => select({ accounts: state.accounts });
+ useAccountStore.getState = () => ({ accounts: state.accounts });
+ return { useAccountStore };
+});
+
+const worker = Object.assign(new EventTarget(), { controller: null as null | { postMessage: ReturnType } });
+const fromWorker = (data: unknown, ports: unknown[] = []) => act(async () => {
+ const event = new Event('message');
+ Object.assign(event, { data, ports });
+ worker.dispatchEvent(event);
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state = { isAuthenticated: true, archiveMode: 'month', archiveEnabled: true, plugins: [], accounts: [] };
+ worker.controller = null;
+ Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: worker });
+});
+
+afterEach(() => {
+ Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: undefined });
+});
+
+describe('the mirror for the worker', () => {
+ it('writes the labels and archive settings once signed in', () => {
+ render( );
+ expect(writeNotificationActionPrefs).toHaveBeenCalledWith({
+ archiveEnabled: true,
+ archiveMode: 'month',
+ pluginsMayVeto: false,
+ labels: { archive: 'action_archive', markRead: 'action_mark_read', reply: 'action_reply', replyPlaceholder: 'reply_placeholder' },
+ });
+ });
+
+ it('writes nothing while signed out', () => {
+ state.isAuthenticated = false;
+ render( );
+ expect(writeNotificationActionPrefs).not.toHaveBeenCalled();
+ });
+
+ it('writes again on signing in, since signing out deleted the store', () => {
+ state.isAuthenticated = false;
+ const { rerender } = render( );
+ state.isAuthenticated = true;
+ rerender( );
+ expect(writeNotificationActionPrefs).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes again when the archive mode or the gate changes, and not otherwise', () => {
+ const { rerender } = render( );
+ rerender( );
+ expect(writeNotificationActionPrefs).toHaveBeenCalledTimes(1);
+ state.archiveMode = 'year';
+ rerender( );
+ expect(writeNotificationActionPrefs).toHaveBeenCalledTimes(2);
+ state.archiveEnabled = false;
+ rerender( );
+ expect(writeNotificationActionPrefs).toHaveBeenCalledTimes(3);
+ expect(writeNotificationActionPrefs.mock.calls[2][0]).toMatchObject({ archiveEnabled: false, archiveMode: 'year' });
+ });
+});
+
+describe('what the worker hears about plugins and logins', () => {
+ it('says when an enabled plugin may stop these actions, and when that ends', () => {
+ state.plugins = [{ enabled: true, permissions: ['email:write'] }];
+ const { rerender } = render( );
+ expect(writeNotificationActionPrefs.mock.calls.at(-1)?.[0]).toMatchObject({ pluginsMayVeto: true });
+ state.plugins = [{ enabled: false, permissions: ['email:write'] }];
+ rerender( );
+ expect(writeNotificationActionPrefs.mock.calls.at(-1)?.[0]).toMatchObject({ pluginsMayVeto: false });
+ });
+
+ it('tells the worker which logins this tab holds, as their fingerprints', async () => {
+ const postMessage = vi.fn();
+ worker.controller = { postMessage };
+ state.accounts = [{ serverUrl: 'https://one.example', username: 'alice@example.org' }];
+ await act(async () => { render( ); });
+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalled());
+ expect(postMessage).toHaveBeenCalledWith({
+ type: 'client-logins',
+ logins: [await loginFingerprint('https://one.example', 'alice@example.org')],
+ });
+ });
+
+ it('tells it again when the logins change', async () => {
+ const postMessage = vi.fn();
+ worker.controller = { postMessage };
+ state.accounts = [{ serverUrl: 'https://one.example', username: 'alice@example.org' }];
+ let view!: ReturnType;
+ await act(async () => { view = render( ); });
+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalledTimes(1));
+ state.accounts = [];
+ await act(async () => { view.rerender( ); });
+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalledTimes(2));
+ expect(postMessage).toHaveBeenLastCalledWith({ type: 'client-logins', logins: [] });
+ });
+});
+
+describe('messages from the worker', () => {
+ const request = { kind: 'notification-action', action: 'mark-read', emailId: 'e1', accountId: 'a', slot: 0, login: 'fp', at: Date.now() };
+
+ it('runs a notification action and answers on its port', async () => {
+ render( );
+ const port = { postMessage: vi.fn() };
+ await fromWorker(request, [port]);
+ expect(runNotificationAction.mock.calls[0][0]).toMatchObject({ action: 'mark-read', emailId: 'e1' });
+ expect(port.postMessage).toHaveBeenCalledWith({ status: 'done' });
+ });
+
+ it('ignores anything else', async () => {
+ render( );
+ await fromWorker({ kind: 'notificationclick', tag: 't' });
+ await fromWorker({ ...request, action: 'delete' });
+ await fromWorker(null);
+ expect(runNotificationAction).not.toHaveBeenCalled();
+ expect(scheduleFlushAll).not.toHaveBeenCalled();
+ });
+
+ it('flushes the outbox on the word of a sync event', async () => {
+ render( );
+ await fromWorker({ kind: 'outbox-flush' });
+ expect(scheduleFlushAll).toHaveBeenCalledWith(0);
+ });
+
+ it('stops listening when it goes', async () => {
+ const { unmount } = render( );
+ unmount();
+ await fromWorker({ kind: 'outbox-flush' });
+ expect(scheduleFlushAll).not.toHaveBeenCalled();
+ });
+
+ it('does nothing in a browser without service workers', () => {
+ Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: undefined });
+ expect(() => render( )).not.toThrow();
+ });
+});
diff --git a/components/providers/notification-actions-host.tsx b/components/providers/notification-actions-host.tsx
new file mode 100644
index 000000000..4077951d3
--- /dev/null
+++ b/components/providers/notification-actions-host.tsx
@@ -0,0 +1,83 @@
+'use client';
+
+import { useEffect, useMemo } from 'react';
+import { useTranslations } from 'next-intl';
+import { useArchiveActionEnabled } from '@/lib/archive-gate';
+import { scheduleFlushAll } from '@/lib/offline/offline-mode';
+import { loginFingerprint } from '@/lib/pwa-notify/login-fingerprint';
+import { isNotificationActionRequest, runNotificationAction } from '@/lib/pwa-notify/page-actions';
+import { pluginsMayVeto } from '@/lib/pwa-notify/plugin-veto';
+import { writeNotificationActionPrefs } from '@/lib/pwa-notify/worker-state';
+import { useAccountStore } from '@/stores/account-store';
+import { useAuthStore } from '@/stores/auth-store';
+import { usePluginStore } from '@/stores/plugin-store';
+import { useSettingsStore } from '@/stores/settings-store';
+
+/**
+ * This tab's end of what the service worker can't do alone: it keeps the
+ * worker's copy of the labels and archive settings current, says which logins
+ * it holds, runs a notification's buttons and flushes the outbox on the
+ * worker's word. Not mounted in Lite (no service worker there).
+ */
+export function NotificationActionsHost() {
+ const t = useTranslations('pwaNotify');
+ const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
+ const archiveMode = useSettingsStore((s) => s.archiveMode);
+ const archiveEnabled = useArchiveActionEnabled();
+ const mayVeto = usePluginStore((s) => pluginsMayVeto(s.plugins));
+ const accounts = useAccountStore((s) => s.accounts);
+ const archive = t('action_archive');
+ const markRead = t('action_mark_read');
+ const reply = t('action_reply');
+ const replyPlaceholder = t('reply_placeholder');
+
+ // Signing out deletes the worker's store, so signing in writes it again.
+ useEffect(() => {
+ if (!isAuthenticated) return;
+ void writeNotificationActionPrefs({
+ archiveEnabled,
+ archiveMode,
+ pluginsMayVeto: mayVeto,
+ labels: { archive, markRead, reply, replyPlaceholder },
+ });
+ }, [isAuthenticated, archiveEnabled, archiveMode, mayVeto, archive, markRead, reply, replyPlaceholder]);
+
+ // Which logins this tab holds: if it stays silent on a click for one of them,
+ // the worker opens the message rather than go round its plugins.
+ const loginKey = useMemo(() => accounts.map((a) => `${a.serverUrl}\n${a.username}`).join('\n\n'), [accounts]);
+ useEffect(() => {
+ const worker = navigator.serviceWorker;
+ if (!worker) return;
+ let stale = false;
+ void (async () => {
+ try {
+ const held = await Promise.all(useAccountStore.getState().accounts.map((a) => loginFingerprint(a.serverUrl, a.username)));
+ // Without a worker `ready` never settles, and nothing needs telling.
+ const target = worker.controller ?? (await worker.ready).active;
+ if (!stale) target?.postMessage({ type: 'client-logins', logins: held });
+ } catch {
+ // The worker counts this tab as not holding them.
+ }
+ })();
+ return () => { stale = true; };
+ }, [loginKey, isAuthenticated]);
+
+ useEffect(() => {
+ const worker = navigator.serviceWorker;
+ if (!worker) return;
+ const onMessage = (event: MessageEvent) => {
+ const message = event.data as { kind?: string } | null;
+ if (message?.kind === 'outbox-flush') {
+ scheduleFlushAll(0);
+ return;
+ }
+ if (message?.kind !== 'notification-action' || !isNotificationActionRequest(message)) return;
+ const port = event.ports[0];
+ void runNotificationAction(message, (status) => port?.postMessage({ status }));
+ };
+ worker.addEventListener('message', onMessage);
+ return () => worker.removeEventListener('message', onMessage);
+ }, []);
+
+ return null;
+}
diff --git a/hooks/use-handoff-files.ts b/hooks/use-handoff-files.ts
new file mode 100644
index 000000000..9ef0eea8e
--- /dev/null
+++ b/hooks/use-handoff-files.ts
@@ -0,0 +1,28 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { subscribeHandoff, takeHandoff, type HandoffKind } from "@/lib/launch-handoff";
+
+/**
+ * The files handed to this part of the app (lib/launch-handoff.ts), one at a
+ * time. Nothing is taken while `active` is false, for a surface that isn't
+ * ready for them yet. `done` moves on to the next file.
+ */
+export function useHandoffFiles(kind: HandoffKind, active: boolean): { file: File | null; done: () => void } {
+ const [files, setFiles] = useState([]);
+
+ useEffect(() => {
+ if (!active) return;
+ const take = () => {
+ for (let handoff = takeHandoff(kind); handoff; handoff = takeHandoff(kind)) {
+ const received = handoff.files;
+ if (received.length > 0) setFiles((waiting) => [...waiting, ...received]);
+ }
+ };
+ take();
+ return subscribeHandoff(kind, take);
+ }, [kind, active]);
+
+ const done = useCallback(() => setFiles((waiting) => waiting.slice(1)), []);
+ return { file: files[0] ?? null, done };
+}
diff --git a/integration/tests/23-do-pwa-launch.spec.ts b/integration/tests/23-do-pwa-launch.spec.ts
new file mode 100644
index 000000000..6d2330b72
--- /dev/null
+++ b/integration/tests/23-do-pwa-launch.spec.ts
@@ -0,0 +1,659 @@
+import { test, expect, type Browser, type BrowserContext, type Page } from '@playwright/test';
+import { accountSwitcher, neutralizeDevOverlay } from './helpers/app';
+import { WEBMAIL_URL } from './helpers/config';
+import { ENT, ENT_PASSWORD, adminContext, contextOptions, getPolicy, jmapAs, putPolicy, requireEntEnv, shot } from './helpers/ent';
+
+/**
+ * The installed app's launches through the real UI: shortcuts, files opened
+ * from the OS, and shares. Chromium can't fire launchQueue from a test, so a
+ * stand-in catches the consumer the app registers, and the spec calls that
+ * consumer the way the browser would. Shares go through the real service
+ * worker as a real form POST. Needs a production build, the only one that
+ * registers the worker.
+ *
+ * BUILD=1 bash desktop-offline-rig/start-prod.sh 3230 pwa-launch-1.0
+ * bash desktop-offline-rig/run-spec.sh 3230 1.0 integration/tests/23-do-pwa-launch.spec.ts
+ */
+
+test.describe.configure({ mode: 'serial' });
+test.setTimeout(180_000);
+
+const RUN = Date.now().toString(36);
+const composer = (page: Page) => page.locator('[data-testid="email-composer"]').first();
+const SHARE_CACHE = 'bulwark-launch-handoff-v1';
+
+type LaunchFile = { name: string; type: string; body: string };
+
+const EML: LaunchFile = {
+ name: 'note.eml',
+ type: 'message/rfc822',
+ body: [
+ 'From: Bob ',
+ 'To: Alice ',
+ `Subject: Launched message ${RUN}`,
+ 'Date: Tue, 03 Nov 2026 10:00:00 +0000',
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ 'Opened from the file system.',
+ '',
+ ].join('\r\n'),
+};
+
+const ICS: LaunchFile = {
+ name: 'invite.ics',
+ type: 'text/calendar',
+ body: [
+ 'BEGIN:VCALENDAR',
+ 'VERSION:2.0',
+ 'PRODID:-//Bulwark//Test//EN',
+ 'BEGIN:VEVENT',
+ `UID:launch-${RUN}@example.org`,
+ 'DTSTAMP:20261103T100000Z',
+ 'DTSTART:20261110T100000Z',
+ 'DTEND:20261110T110000Z',
+ `SUMMARY:Launched event ${RUN}`,
+ 'END:VEVENT',
+ 'END:VCALENDAR',
+ '',
+ ].join('\r\n'),
+};
+
+const VCF: LaunchFile = {
+ name: 'people.vcf',
+ type: 'text/vcard',
+ body: ['BEGIN:VCARD', 'VERSION:3.0', `FN:Launched Person ${RUN}`, `EMAIL:launched-${RUN}@example.org`, 'END:VCARD', ''].join('\r\n'),
+};
+
+/** Stands in for the browser's launchQueue, keeping the consumer the app sets. */
+function catchLaunchConsumer() {
+ Object.defineProperty(window, 'launchQueue', {
+ configurable: true,
+ value: {
+ setConsumer(fn: unknown) {
+ (window as unknown as { __launch: unknown }).__launch = fn;
+ },
+ },
+ });
+}
+
+async function launch(page: Page, opts: { target?: string; files?: LaunchFile[] }): Promise {
+ await page.waitForFunction(() => typeof (window as unknown as { __launch?: unknown }).__launch === 'function');
+ await page.evaluate(({ target, files }) => {
+ const consumer = (window as unknown as { __launch: (params: unknown) => void }).__launch;
+ consumer({
+ targetURL: new URL(target, window.location.origin).href,
+ ...(files.length > 0 ? {
+ files: files.map((f) => ({ kind: 'file', getFile: async () => new File([f.body], f.name, { type: f.type }) })),
+ } : {}),
+ });
+ }, { target: opts.target ?? '/', files: opts.files ?? [] });
+}
+
+async function signIn(page: Page, email: string): Promise {
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await page.fill('#username', email);
+ await page.fill('#password', ENT_PASSWORD);
+ await page.click('button[type="submit"]');
+ await accountSwitcher(page).waitFor({ state: 'visible', timeout: 60_000 });
+}
+
+/** A new window lands signed out or signed in, depending on what can be restored. */
+async function signInIfAsked(page: Page, email: string): Promise {
+ const login = page.locator('#username');
+ await expect(login.or(accountSwitcher(page))).toBeVisible({ timeout: 60_000 });
+ if (await login.isVisible()) await signIn(page, email);
+}
+
+async function launchContext(browser: Browser, opts: Parameters[0] = {}): Promise {
+ const context = await browser.newContext({ ...contextOptions(), ...opts });
+ await context.addInitScript(catchLaunchConsumer);
+ return context;
+}
+
+async function signedIn(browser: Browser, opts: Parameters[0] = {}): Promise {
+ const page = await (await launchContext(browser, opts)).newPage();
+ await neutralizeDevOverlay(page);
+ await page.goto('/');
+ await signIn(page, ENT.alice);
+ return page;
+}
+
+/** A real form POST to the share target, as the OS's share sheet sends it. */
+async function postShare(page: Page, fields: Record, files: LaunchFile[]): Promise {
+ await page.evaluate(({ fields: values, files: list }) => {
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.enctype = 'multipart/form-data';
+ form.action = '/protocol/share';
+ for (const [name, value] of Object.entries(values)) {
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = name;
+ input.value = value;
+ form.append(input);
+ }
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.name = 'files';
+ input.multiple = true;
+ const data = new DataTransfer();
+ for (const f of list) data.items.add(new File([f.body], f.name, { type: f.type }));
+ input.files = data.files;
+ form.append(input);
+ document.body.append(form);
+ form.submit();
+ }, { fields, files });
+}
+
+async function workerReady(page: Page): Promise {
+ const active = await page.evaluate(() => navigator.serviceWorker.ready.then((r) => !!r.active));
+ expect(active).toBe(true);
+}
+
+/** The question a share has to pass, wherever it came from. */
+const startMessage = (page: Page) => page.getByRole('button', { name: 'Start message', exact: true });
+const dontStart = (page: Page) => page.getByRole('button', { name: "Don't start", exact: true });
+
+const HOSTILE = 'http://hostile.example';
+
+/** A page on another origin that POSTs to the share target as soon as it loads. Nobody clicks. */
+function hostilePage(opts: { subject: string; fileName?: string }): string {
+ return `hostile `;
+}
+
+async function hostileTab(context: BrowserContext, opts: Parameters[0]): Promise {
+ await context.route(`${HOSTILE}/**`, (route) => route.fulfill({ contentType: 'text/html', body: hostilePage(opts) }));
+ const tab = await context.newPage();
+ await tab.goto(`${HOSTILE}/`);
+ return tab;
+}
+
+/** Every message on the server with this subject. */
+async function draftsWithSubject(subject: string): Promise {
+ const client = await jmapAs(ENT.alice);
+ const res = await client.request([['Email/query', { accountId: client.accountId, filter: { subject } }, 'q']]);
+ return res.methodResponses[0][1].ids as string[];
+}
+
+async function deleteDrafts(ids: string[]): Promise {
+ if (ids.length === 0) return;
+ const client = await jmapAs(ENT.alice);
+ await client.request([['Email/set', { accountId: client.accountId, destroy: ids }, 'd']]);
+}
+
+const storedShareEntries = (page: Page) => page.evaluate(async (name) => {
+ if (!(await caches.has(name))) return 0;
+ return (await (await caches.open(name)).keys()).length;
+}, SHARE_CACHE);
+
+test.beforeAll(() => requireEntEnv());
+
+test.describe('manifest', () => {
+ test('offers shortcuts, file handlers and the share target, in the browser language', async ({ browser }) => {
+ const context = await browser.newContext(contextOptions());
+ const res = await context.request.get('/manifest.webmanifest', { headers: { 'Accept-Language': 'de-DE,de;q=0.9' } });
+ expect(res.ok()).toBe(true);
+ const manifest = await res.json();
+ expect(manifest.shortcuts.map((s: { name: string; url: string }) => [s.name, s.url])).toEqual([
+ ['Neue Nachricht', '/?compose=1'],
+ ['Kalender', '/calendar'],
+ ['Kontakte', '/contacts'],
+ ]);
+ expect(manifest.file_handlers.map((h: { action: string }) => h.action)).toEqual(['/mail', '/calendar', '/contacts']);
+ expect(manifest.share_target).toMatchObject({ action: '/protocol/share', method: 'POST', enctype: 'multipart/form-data' });
+ expect(manifest.protocol_handlers).toHaveLength(2);
+ await context.close();
+ });
+
+ test('every address in it answers', async ({ browser }) => {
+ const context = await browser.newContext(contextOptions());
+ const manifest = await (await context.request.get('/manifest.webmanifest')).json();
+ for (const shortcut of manifest.shortcuts) {
+ expect((await context.request.get(shortcut.url)).ok(), shortcut.url).toBe(true);
+ expect((await context.request.get(shortcut.icons[0].src)).ok(), shortcut.icons[0].src).toBe(true);
+ }
+ for (const handler of manifest.file_handlers) {
+ expect((await context.request.get(handler.action)).ok(), handler.action).toBe(true);
+ }
+ await context.close();
+ });
+});
+
+test.describe('share target', () => {
+ test('files and a link go through the service worker into a new draft', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await workerReady(page);
+
+ const subject = `Shared ${RUN}`;
+ await postShare(page, { title: subject, text: 'Have a look', url: 'https://example.org/page' }, [
+ { name: `shared-${RUN}.txt`, type: 'text/plain', body: 'shared bytes' },
+ ]);
+ await page.waitForURL((url) => url.pathname.endsWith('/') || !url.pathname.includes('protocol'));
+ await startMessage(page).click({ timeout: 60_000 });
+ await signInIfAsked(page, ENT.alice);
+
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ await expect(composer(page).getByPlaceholder(/subject/i)).toHaveValue(subject);
+ await expect(composer(page).locator('[contenteditable="true"]').first()).toContainText('https://example.org/page');
+ await expect(composer(page).getByText(`shared-${RUN}.txt`)).toBeVisible();
+ // It reached the app through the worker's store, not the server's fallback.
+ await expect(page.getByText("The shared files couldn't be kept")).toHaveCount(0);
+ await expect.poll(() => new URL(page.url()).hash).toBe('');
+ await expect.poll(() => storedShareEntries(page)).toBe(0);
+ await shot(page, 'pwa-launch-share');
+ await page.context().close();
+ });
+
+ test('survives a sign-in that reloads the page', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/');
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await workerReady(page);
+
+ await postShare(page, { url: 'https://example.org/waited' }, [{ name: `waited-${RUN}.txt`, type: 'text/plain', body: 'x' }]);
+ await startMessage(page).click({ timeout: 60_000 });
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await expect.poll(() => storedShareEntries(page)).toBe(3);
+ // What SSO does: away and back, in the same tab.
+ await page.reload();
+ await signIn(page, ENT.alice);
+
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ await expect(composer(page).getByText(`waited-${RUN}.txt`)).toBeVisible();
+ await expect.poll(() => storedShareEntries(page)).toBe(0);
+ await page.context().close();
+ });
+
+ test('without a service worker the link still arrives and the app says the files did not', async ({ browser }) => {
+ const page = await signedIn(browser, { serviceWorkers: 'block' });
+ await postShare(page, { url: 'https://example.org/no-worker' }, [{ name: 'lost.txt', type: 'text/plain', body: 'x' }]);
+ await page.waitForLoadState('domcontentloaded');
+ await startMessage(page).click({ timeout: 60_000 });
+ await signInIfAsked(page, ENT.alice);
+
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ await expect(composer(page).locator('[contenteditable="true"]').first()).toContainText('https://example.org/no-worker');
+ await expect(composer(page).getByText('lost.txt')).toHaveCount(0);
+ await expect(page.getByText("The shared files couldn't be kept").first()).toBeVisible();
+ await page.context().close();
+ });
+
+ test('the server takes the POST from outside the origin, which /api/ would refuse', async ({ browser }) => {
+ const context = await browser.newContext(contextOptions());
+ const res = await context.request.post('/protocol/share', {
+ headers: { Origin: 'https://other.example', 'Sec-Fetch-Site': 'cross-site' },
+ multipart: { url: 'https://example.org/direct' },
+ maxRedirects: 0,
+ });
+ expect(res.status()).toBe(303);
+ const location = new URL(res.headers().location, 'http://x.invalid');
+ // In the fragment: shared text stays out of access logs.
+ expect(location.search).toBe('');
+ const fragment = new URLSearchParams(location.hash.slice(1));
+ expect(fragment.get('share')).toBe('unavailable');
+ expect(fragment.get('share_url')).toBe('https://example.org/direct');
+ await context.close();
+ });
+
+ test('long non-Latin text fits the address the fallback sends on', async ({ browser }) => {
+ const context = await browser.newContext(contextOptions());
+ const res = await context.request.post('/protocol/share', {
+ multipart: { text: 'あ'.repeat(3000) },
+ maxRedirects: 0,
+ });
+ expect(res.status()).toBe(303);
+ const location = res.headers().location;
+ expect(location.length).toBeLessThan(4000);
+ expect((await context.request.get(location)).ok()).toBe(true);
+ await context.close();
+ });
+});
+
+test.describe('a share nobody asked for', () => {
+ test('a POST from another site leaves no draft on the server and asks first', async ({ browser }) => {
+ const signedInPage = await signedIn(browser);
+ await workerReady(signedInPage);
+ const subject = `hostile-${RUN}-a`;
+ const tab = await hostileTab(signedInPage.context(), { subject, fileName: `invoice-${RUN}.exe` });
+ await tab.waitForURL((url) => url.href.startsWith(WEBMAIL_URL));
+
+ // The question comes before anything else, also before a sign-in.
+ await expect(startMessage(tab)).toBeVisible({ timeout: 30_000 }).catch(() => {});
+ if (await startMessage(tab).isVisible()) {
+ await expect(tab.getByTestId('share-confirm-details')).toContainText(`invoice-${RUN}.exe`);
+ } else {
+ await signInIfAsked(tab, ENT.alice);
+ }
+ await tab.waitForTimeout(6000);
+ const drafts = await draftsWithSubject(subject);
+ await deleteDrafts(drafts);
+ expect(drafts).toEqual([]);
+ await expect(composer(tab)).toHaveCount(0);
+ await expect(startMessage(tab)).toBeVisible();
+ await shot(tab, 'pwa-launch-share-confirm');
+
+ // Refused: what it stored goes too.
+ await dontStart(tab).click();
+ await expect.poll(() => storedShareEntries(tab)).toBe(0);
+ await expect(composer(tab)).toHaveCount(0);
+ await signedInPage.context().close();
+ });
+
+ test('agreed, it is only the starting state: no draft until the first real edit', async ({ browser }) => {
+ const signedInPage = await signedIn(browser);
+ await workerReady(signedInPage);
+ const subject = `hostile-${RUN}-b`;
+ const tab = await hostileTab(signedInPage.context(), { subject, fileName: `kept-${RUN}.txt` });
+ await tab.waitForURL((url) => url.href.startsWith(WEBMAIL_URL));
+ await startMessage(tab).click({ timeout: 60_000 });
+ await signInIfAsked(tab, ENT.alice);
+ await expect(composer(tab).getByText(`kept-${RUN}.txt`)).toBeVisible({ timeout: 30_000 });
+ await expect(composer(tab).getByPlaceholder(/subject/i)).toHaveValue(subject);
+
+ await tab.waitForTimeout(6000);
+ expect(await draftsWithSubject(subject)).toEqual([]);
+
+ // Leaving doesn't save it either.
+ await tab.evaluate(() => { window.dispatchEvent(new Event('beforeunload')); });
+ await tab.waitForTimeout(3000);
+ expect(await draftsWithSubject(subject)).toEqual([]);
+
+ // The user's own edit: from here it is a draft like any other.
+ await composer(tab).getByPlaceholder(/subject/i).fill(`${subject} edited`);
+ await expect(composer(tab).getByPlaceholder(/subject/i)).toHaveValue(`${subject} edited`);
+ await expect.poll(() => draftsWithSubject(subject), { timeout: 20_000 }).toHaveLength(1);
+ await deleteDrafts(await draftsWithSubject(subject));
+ await signedInPage.context().close();
+ });
+
+ test('a hidden frame stores nothing', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/');
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await workerReady(page);
+ // From the app's own origin: another site's frame doesn't reach this worker
+ // at all in Chromium (partitioned storage), so only this shows the check.
+ await page.evaluate(() => {
+ const frame = document.createElement('iframe');
+ frame.name = 'hidden-share';
+ frame.style.display = 'none';
+ document.body.append(frame);
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.enctype = 'multipart/form-data';
+ form.action = '/protocol/share';
+ form.target = 'hidden-share';
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = 'title';
+ input.value = 'frame';
+ form.append(input);
+ document.body.append(form);
+ form.submit();
+ });
+ await page.waitForTimeout(3000);
+ expect(await storedShareEntries(page)).toBe(0);
+ await page.context().close();
+ });
+
+ test('text in an address anyone can link to asks first too', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await page.goto(`/#share=unavailable&share_title=${encodeURIComponent(`linked-${RUN}`)}&share_text=hello`);
+ await expect(startMessage(page)).toBeVisible({ timeout: 30_000 });
+ await expect(composer(page)).toHaveCount(0);
+ await dontStart(page).click();
+ await expect(composer(page)).toHaveCount(0);
+ await page.context().close();
+ });
+});
+
+test.describe('a handoff while a composer is open', () => {
+ test('one set aside by reading a message is not replaced by the next', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await page.locator('[data-testid="email-list-item"]').first().waitFor({ timeout: 30_000 });
+ const subject = `setaside${RUN}`;
+ await launch(page, { target: '/?compose=1' });
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ await composer(page).getByPlaceholder(/subject/i).fill(subject);
+ await expect(composer(page).getByPlaceholder(/subject/i)).toHaveValue(subject);
+ // Reading a message suspends the composer before its autosave ran.
+ await page.locator('[data-testid="email-list-item"]').first().click();
+ await expect(composer(page)).toHaveCount(0);
+ await page.waitForTimeout(2100);
+ await launch(page, { target: '/?compose=1' });
+ await expect(page.getByText('Close this message to start the next one.').first()).toBeVisible({ timeout: 10_000 });
+ await expect(composer(page)).toHaveCount(0);
+ await expect(page.getByText(subject).first()).toBeVisible();
+ await page.context().close();
+ });
+
+ test('two at once: the second waits until the first composer closes', async ({ browser }) => {
+ const page = await signedIn(browser);
+ // Let the page settle after the sign-in: the composer shouldn't race the first mail load.
+ await page.waitForTimeout(3000);
+ await launch(page, { target: '/?compose=1' });
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ const subject = `kept-open-${RUN}`;
+ await composer(page).getByPlaceholder(/subject/i).fill(subject);
+ await expect(composer(page).getByPlaceholder(/subject/i)).toHaveValue(subject);
+
+ await page.waitForTimeout(2100);
+ await launch(page, { target: '/?compose=1' });
+ await expect(page.getByText('Close this message to start the next one.').first()).toBeVisible({ timeout: 10_000 });
+ await expect(composer(page).getByPlaceholder(/subject/i)).toHaveValue(subject);
+
+ await page.locator('[data-testid="composer-close"]').first().click();
+ await expect(composer(page).getByPlaceholder(/subject/i)).toHaveValue('', { timeout: 15_000 });
+ await deleteDrafts(await draftsWithSubject(subject));
+ await page.context().close();
+ });
+
+ test('a .vcf launch saves what was just typed before leaving the composer', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/?compose=1' });
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ const subject = `typedfirst${RUN}`;
+ await composer(page).getByPlaceholder(/subject/i).fill(subject);
+ // Well inside the autosave's 2 seconds.
+ await launch(page, { target: '/contacts', files: [VCF] });
+ await page.waitForURL(/\/contacts/);
+ await expect(page.getByText(`Launched Person ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await expect.poll(() => draftsWithSubject(subject), { timeout: 10_000 }).toHaveLength(1);
+ await deleteDrafts(await draftsWithSubject(subject));
+ await page.context().close();
+ });
+});
+
+test.describe('file launches', () => {
+ test('.eml opens in the viewer, over the page', async ({ browser }) => {
+ const page = await signedIn(browser);
+ const before = new URL(page.url()).pathname;
+ await launch(page, { target: '/mail', files: [EML] });
+ await expect(page.getByRole('heading', { name: `Launched message ${RUN}` })).toBeVisible({ timeout: 20_000 });
+ expect(new URL(page.url()).pathname).toBe(before);
+ await expect(page.getByRole('button', { name: 'Download', exact: true }).first()).toBeVisible();
+ await shot(page, 'pwa-launch-eml');
+ await page.context().close();
+ });
+
+ test('.eml opens before signing in', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/');
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await launch(page, { target: '/mail', files: [EML] });
+ await expect(page.getByRole('heading', { name: `Launched message ${RUN}` })).toBeVisible({ timeout: 20_000 });
+ await page.context().close();
+ });
+
+ test('.eml with downloads blocked: the viewer opens, with nothing to save', async ({ browser }) => {
+ const admin = await adminContext(browser);
+ const saved = await getPolicy(admin);
+ const organisation = (saved.organisation ?? {}) as Record;
+ await putPolicy(admin, {
+ ...saved,
+ organisation: {
+ ...organisation,
+ devices: { ...((organisation.devices ?? {}) as object), noDownloads: true },
+ },
+ });
+ try {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/mail', files: [EML] });
+ await expect(page.getByRole('heading', { name: `Launched message ${RUN}` })).toBeVisible({ timeout: 20_000 });
+ await expect(page.getByRole('button', { name: 'Download', exact: true })).toHaveCount(0);
+ await page.context().close();
+ } finally {
+ await putPolicy(admin, saved);
+ await admin.close();
+ }
+ });
+
+ test('.eml without a connection or the viewer chunk: a message, not the error page', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await page.context().setOffline(true);
+ await launch(page, { target: '/mail', files: [EML] });
+ await expect(page.getByText("The file couldn't be opened").first()).toBeVisible({ timeout: 20_000 });
+ await expect(accountSwitcher(page)).toBeVisible();
+
+ await page.context().setOffline(false);
+ await launch(page, { target: '/mail', files: [EML] });
+ await expect(page.getByRole('heading', { name: `Launched message ${RUN}` })).toBeVisible({ timeout: 20_000 });
+ await page.context().close();
+ });
+
+ test('.ics goes to the calendar import, which the server parses', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/calendar', files: [ICS] });
+ await page.waitForURL(/\/calendar/);
+ await expect(page.getByText(`Launched event ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await shot(page, 'pwa-launch-ics');
+ await page.context().close();
+ });
+
+ test('.ics while offline says the server is needed, and carries on once back', async ({ browser }) => {
+ const page = await signedIn(browser);
+ // Into the calendar first: its code isn't on the device without offline mode.
+ await launch(page, { target: '/calendar' });
+ await page.waitForURL(/\/calendar/);
+ await page.context().setOffline(true);
+ await launch(page, { target: '/calendar', files: [ICS] });
+ await expect(page.getByText('Importing a calendar file needs a connection to the server.')).toBeVisible({ timeout: 20_000 });
+ await shot(page, 'pwa-launch-ics-offline');
+
+ await page.context().setOffline(false);
+ await expect(page.getByText(`Launched event ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await page.context().close();
+ });
+
+ test('.vcf goes to the contacts import, parsed in the browser', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/contacts', files: [VCF] });
+ await page.waitForURL(/\/contacts/);
+ await expect(page.getByText(`Launched Person ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await shot(page, 'pwa-launch-vcf');
+ await page.context().close();
+ });
+
+ test('a file launched before signing in waits for it', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/');
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await launch(page, { target: '/contacts', files: [VCF] });
+ await expect(page.locator('#username')).toBeVisible();
+ await signIn(page, ENT.alice);
+ await page.waitForURL(/\/contacts/);
+ await expect(page.getByText(`Launched Person ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await page.context().close();
+ });
+
+ test('a file launched into a signed-in page with a reload on the way still arrives', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/');
+ await page.locator('#username').waitFor({ state: 'visible', timeout: 60_000 });
+ await launch(page, { target: '/calendar', files: [ICS] });
+ await expect.poll(() => storedShareEntries(page)).toBe(3);
+ await page.reload();
+ await signIn(page, ENT.alice);
+ await page.waitForURL(/\/calendar/);
+ await expect(page.getByText(`Launched event ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await expect.poll(() => storedShareEntries(page)).toBe(0);
+ await page.context().close();
+ });
+});
+
+test.describe('shortcuts', () => {
+ test('New message opens a composer from the address, once, and clears the address', async ({ browser }) => {
+ const page = await (await launchContext(browser)).newPage();
+ await page.goto('/?compose=1');
+ await signIn(page, ENT.alice);
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ expect(new URL(page.url()).search).toBe('');
+ await page.context().close();
+ });
+
+ test('New message in an open window', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await expect(composer(page)).toHaveCount(0);
+ await launch(page, { target: '/?compose=1' });
+ await expect(composer(page)).toBeVisible({ timeout: 30_000 });
+ await page.context().close();
+ });
+
+ test('Calendar and Contacts in an open window', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/calendar' });
+ await page.waitForURL(/\/calendar/);
+ await launch(page, { target: '/contacts' });
+ await page.waitForURL(/\/contacts/);
+ await page.context().close();
+ });
+
+ test('the plain app icon leaves an open window where it is', async ({ browser }) => {
+ const page = await signedIn(browser);
+ await launch(page, { target: '/calendar' });
+ await page.waitForURL(/\/calendar/);
+ await launch(page, { target: '/' });
+ await page.waitForTimeout(1000);
+ expect(new URL(page.url()).pathname).toMatch(/\/calendar(\/|$)/);
+ await expect(composer(page)).toHaveCount(0);
+ await page.context().close();
+ });
+});
+
+test.describe('in the Pro shell', () => {
+ const proOn = () => {
+ const key = 'settings-storage';
+ const parsed = JSON.parse(localStorage.getItem(key) ?? '{"state":{},"version":0}');
+ parsed.state = { ...parsed.state, proInterface: true };
+ localStorage.setItem(key, JSON.stringify(parsed));
+ };
+
+ test('a shared file reaches the composer tab, and a .ics the calendar tab', async ({ browser }) => {
+ const context = await launchContext(browser);
+ await context.addInitScript(proOn);
+ const page = await context.newPage();
+ await page.goto('/');
+ await signIn(page, ENT.alice);
+ await page.waitForURL(/\/pro/);
+ await workerReady(page);
+
+ await postShare(page, { url: 'https://example.org/pro' }, [{ name: `pro-${RUN}.txt`, type: 'text/plain', body: 'x' }]);
+ await startMessage(page).click({ timeout: 60_000 });
+ await signInIfAsked(page, ENT.alice);
+ await page.waitForURL(/\/pro/);
+ await expect(page.getByText(`pro-${RUN}.txt`).first()).toBeVisible({ timeout: 30_000 });
+
+ await launch(page, { target: '/calendar', files: [ICS] });
+ await expect(page.getByText(`Launched event ${RUN}`).first()).toBeVisible({ timeout: 30_000 });
+ await shot(page, 'pwa-launch-pro');
+ await context.close();
+ });
+});
diff --git a/integration/tests/23-do-pwa-notify.spec.ts b/integration/tests/23-do-pwa-notify.spec.ts
new file mode 100644
index 000000000..5867c9c29
--- /dev/null
+++ b/integration/tests/23-do-pwa-notify.spec.ts
@@ -0,0 +1,566 @@
+import { test, expect, type BrowserContext, type Page, type Worker } from '@playwright/test';
+import { JMAP_URL } from './helpers/config';
+import { ENT, adminContext, deliver, jmapAs, requireEntEnv, userPage, withPolicy } from './helpers/ent';
+
+/**
+ * A notification's Archive, Mark read and Reply, and Background Sync, in
+ * Chromium with the real service worker of a production build, the real
+ * /api/push/preview and /api/push/action, and a VM 106 test Stalwart.
+ *
+ * Headless Chromium has no toasts to click, and a page can't make a browser
+ * send a trusted notificationclick. So the spec dispatches the event inside
+ * the real worker, on its real listener: an Event carrying `action`, the
+ * `notification` the browser really shows, and a waitUntil of its own
+ * (ExtendableEvent.waitUntil refuses a synthetic event). Everything after
+ * that is real: matchAll, postMessage to the page, the cookies on the route.
+ * What can't run this way is openWindow, focus and navigate, which want the
+ * browser's user activation, so those are recorded on the worker's side and
+ * the spec then opens the recorded URL itself.
+ *
+ * The account is ent-dave, whom the other specs leave alone: the one-message
+ * notification needs an Inbox with exactly one unread message.
+ */
+
+test.describe.configure({ mode: 'serial' });
+test.setTimeout(180_000);
+// The headless shell denies notifications whatever is granted; full Chromium
+// in headless mode really shows them, buttons and all, to getNotifications.
+test.use({ channel: 'chromium' });
+
+const RUN = Date.now().toString(36);
+let serial = 0;
+const USER = ENT.dave;
+
+interface ShownNotification {
+ title: string;
+ data: Record;
+ actions: Array<{ action: string; title: string; type?: string }>;
+}
+
+async function workerOf(context: BrowserContext, page: Page): Promise {
+ // A production build registers the worker; the dev server removes it.
+ await page.evaluate(() => navigator.serviceWorker.ready.then(() => undefined));
+ await expect.poll(() => context.serviceWorkers().length, { timeout: 30_000 }).toBeGreaterThan(0);
+ const sw = context.serviceWorkers().at(-1)!;
+ // What needs the user activation a dispatched click doesn't have.
+ await sw.evaluate(() => {
+ const self_ = globalThis as unknown as { __opened: string[]; __posts: string[]; clients: Record; fetch: typeof fetch };
+ if (self_.__opened) return;
+ self_.__opened = [];
+ self_.__posts = [];
+ self_.clients.openWindow = async (url: string) => { self_.__opened.push(url); return null; };
+ const realFetch = self_.fetch.bind(globalThis);
+ self_.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method === 'POST') self_.__posts.push(String(input));
+ return realFetch(input, init);
+ }) as typeof fetch;
+ });
+ return sw;
+}
+
+/** The real listener, with what the browser would pass. Resolves when its waitUntil settled. */
+async function click(sw: Worker, action: string, data: Record, reply?: string): Promise {
+ await sw.evaluate(async ({ action: a, data: d, reply: r }) => {
+ const waits: Promise[] = [];
+ const event = new Event('notificationclick') as Event & Record;
+ Object.assign(event, {
+ action: a,
+ reply: r ?? null,
+ notification: { data: d, tag: 'spec', close() {} },
+ waitUntil: (p: Promise) => waits.push(p),
+ });
+ self.dispatchEvent(event);
+ await Promise.all(waits);
+ }, { action, data, reply });
+}
+
+async function pushed(sw: Worker, accountId: string, emailId: string): Promise {
+ return sw.evaluate(async ({ accountId: account, emailId: id }) => {
+ const waits: Promise[] = [];
+ const event = new Event('push') as Event & Record;
+ Object.assign(event, {
+ data: { json: () => ({ kind: 'jmap-email-push', accountId: account, emailIds: [id] }) },
+ waitUntil: (p: Promise) => waits.push(p),
+ });
+ self.dispatchEvent(event);
+ await Promise.all(waits);
+ const registration = (self as unknown as { registration: ServiceWorkerRegistration }).registration;
+ const [shown] = await registration.getNotifications({ tag: `bulwark-mail:${account}` });
+ return { title: shown.title, data: shown.data, actions: [...(shown as unknown as { actions: ShownNotification['actions'] }).actions] };
+ }, { accountId, emailId });
+}
+
+async function opened(sw: Worker): Promise {
+ return sw.evaluate(() => (globalThis as unknown as { __opened: string[] }).__opened.splice(0));
+}
+
+async function routePosts(sw: Worker): Promise {
+ return sw.evaluate(() => (globalThis as unknown as { __posts: string[] }).__posts.splice(0));
+}
+
+/** Everything unread in the Inbox read, then one new message: what makes a notification name it. */
+async function oneUnread(): Promise<{ id: string; subject: string; accountId: string }> {
+ const client = await jmapAs(USER);
+ const inbox = await client.mailboxByRole('inbox');
+ const query = await client.request([
+ ['Email/query', { accountId: client.accountId, filter: { inMailbox: inbox!.id, notKeyword: '$seen' } }, 'q'],
+ ]);
+ const unread: string[] = query.methodResponses[0][1].ids;
+ if (unread.length > 0) {
+ await client.request([['Email/set', {
+ accountId: client.accountId,
+ update: Object.fromEntries(unread.map((id) => [id, { 'keywords/$seen': true }])),
+ }, 's']]);
+ }
+ const subject = `Notify ${RUN} ${++serial}`;
+ await deliver({ from: ENT.bob, to: [USER], subject, text: 'Please answer.' });
+ const email = await client.waitForEmail(subject, { mailboxId: inbox!.id, timeoutMs: 30_000 });
+ return { id: email.id, subject, accountId: client.accountId };
+}
+
+async function serverCopy(emailId: string): Promise<{ keywords: Record; mailboxIds: Record; receivedAt: string }> {
+ const client = await jmapAs(USER);
+ const res = await client.request([['Email/get', { accountId: client.accountId, ids: [emailId], properties: ['keywords', 'mailboxIds', 'receivedAt'] }, 'g']]);
+ return res.methodResponses[0][1].list[0];
+}
+
+async function archiveFolderId(): Promise {
+ const client = await jmapAs(USER);
+ return (await client.mailboxByRole('archive'))?.id;
+}
+
+test.beforeAll(() => requireEntEnv());
+
+test.describe('with the app open', () => {
+ let page: Page;
+ let context: BrowserContext;
+ let sw: Worker;
+
+ test.beforeAll(async ({ browser }) => {
+ page = await userPage(browser, USER);
+ context = page.context();
+ await context.grantPermissions(['notifications']);
+ sw = await workerOf(context, page);
+ // The mirror reaches the worker's store after the app has started.
+ await expect.poll(() => sw.evaluate(async () => {
+ const cache = await caches.open('bulwark-push-state-v1');
+ const hit = await cache.match(`${self.location.origin}/__push-state/actions`);
+ return hit ? (await hit.json()).labels?.archive : null;
+ }), { timeout: 30_000 }).toBe('Archive');
+ });
+
+ test.afterAll(async () => {
+ await context.close();
+ });
+
+ test('a push for one message shows the buttons the browser has room for', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ expect(shown.title).toContain(ENT.bob.split('@')[0]);
+ expect(shown.data).toMatchObject({ kind: 'email', emailId: mail.id, accountId: mail.accountId });
+ expect(typeof shown.data.login).toBe('string');
+ const max = await sw.evaluate(() => (Notification as unknown as { maxActions: number }).maxActions);
+ const names = shown.actions.map((a) => a.action);
+ expect(names.length).toBe(Math.min(3, max));
+ expect(names).toContain('reply');
+ expect(names).toContain('archive');
+ expect(shown.actions.find((a) => a.action === 'archive')?.title).toBe('Archive');
+ // Chromium has `reply` on the event: the text field.
+ expect(shown.actions.find((a) => a.action === 'reply')?.type).toBe('text');
+ });
+
+ test('a group of messages gets no buttons', async () => {
+ const client = await jmapAs(USER);
+ const first = await oneUnread();
+ const subject = `Notify ${RUN} second`;
+ await deliver({ from: ENT.bob, to: [USER], subject, text: 'Another.' });
+ const second = await client.waitForEmail(subject, { timeoutMs: 30_000 });
+ const shown = await pushed(sw, first.accountId, second.id);
+ expect(shown.data.kind).toBe('mail-list');
+ expect(shown.actions).toEqual([]);
+ });
+
+ test('Mark read goes to the open tab, which marks it in the list too, not to the route', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await routePosts(sw);
+ await click(sw, 'mark-read', shown.data);
+ await expect.poll(async () => (await serverCopy(mail.id)).keywords.$seen === true, { timeout: 15_000 }).toBe(true);
+ expect(await routePosts(sw)).toEqual([]);
+ expect(await opened(sw)).toEqual([]);
+ });
+
+ test('Archive goes to the open tab and files the message by the store', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await routePosts(sw);
+ await click(sw, 'archive', shown.data);
+ const client = await jmapAs(USER);
+ const inbox = await client.mailboxByRole('inbox');
+ await expect.poll(async () => !(await serverCopy(mail.id)).mailboxIds[inbox!.id], { timeout: 20_000 }).toBe(true);
+ const archive = await archiveFolderId();
+ expect(archive).toBeTruthy();
+ expect(Object.keys((await serverCopy(mail.id)).mailboxIds)).toEqual([archive]);
+ expect(await routePosts(sw)).toEqual([]);
+ });
+
+ test('a body click still opens the message and runs nothing', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await routePosts(sw);
+ // focus() needs the activation a dispatched click lacks, so this ends in openWindow.
+ await click(sw, '', shown.data);
+ const urls = await opened(sw);
+ expect(urls).toHaveLength(1);
+ expect(urls[0]).toContain(`/mail/message/${mail.id}`);
+ expect(urls[0]).not.toContain('reply=1');
+ expect(await routePosts(sw)).toEqual([]);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ });
+
+ test('Reply opens the composer in the open tab, with the text typed on the notification', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await routePosts(sw);
+ await click(sw, 'reply', shown.data, `Typed on the toast ${RUN}`);
+ await expect.poll(async () => page.evaluate((subjectText) => {
+ const inputs = [...document.querySelectorAll('input')] as HTMLInputElement[];
+ return inputs.some((input) => input.value === `Re: ${subjectText}`);
+ }, mail.subject), { timeout: 20_000 }).toBe(true);
+ await expect(page.getByText(`Typed on the toast ${RUN}`).first()).toBeVisible({ timeout: 10_000 });
+ expect(await routePosts(sw)).toEqual([]);
+ expect(await opened(sw)).toEqual([]);
+ });
+});
+
+test.describe('Background Sync', () => {
+ test('a queued change registers the tag, and a sync event makes a tab that missed `online` flush it', async ({ browser }) => {
+ const page = await userPage(browser, USER);
+ const context = page.context();
+ await context.grantPermissions(['notifications', 'background-sync']);
+ const sw = await workerOf(context, page);
+ await page.addInitScript(() => {
+ const w = window as unknown as { __syncTags: string[] };
+ w.__syncTags = [];
+ const register = SyncManager.prototype.register;
+ SyncManager.prototype.register = function patched(tag: string) {
+ w.__syncTags.push(tag);
+ return register.call(this, tag);
+ };
+ });
+ await page.goto('/settings/backup/offline');
+ const toggle = page.getByTestId('offline-switch');
+ await expect(toggle).toBeVisible({ timeout: 30_000 });
+ if ((await toggle.getAttribute('aria-checked')) !== 'true') await toggle.click();
+ await expect(page.getByTestId('offline-status')).toContainText('updated', { timeout: 180_000 });
+ await page.goto('/mail');
+ await expect(page.locator('[data-testid="email-list-item"]').first()).toBeVisible({ timeout: 60_000 });
+
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+
+ // The mail server is gone, the browser still online: no `online` event will come.
+ const block = `${new URL(JMAP_URL).origin}/**`;
+ await context.route(block, (route) => route.abort('internetdisconnected'));
+ await page.keyboard.press('Shift+G');
+ await expect(page.getByTestId('offline-banner')).toContainText("The mail server can't be reached", { timeout: 60_000 });
+
+ // The tab queues the change, as it does for its own Mark read button.
+ await click(sw, 'mark-read', shown.data);
+ await expect.poll(() => page.evaluate(() => (window as unknown as { __syncTags: string[] }).__syncTags)).toContain('bulwark-outbox');
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+
+ await context.unroute(block);
+ await sw.evaluate(async () => {
+ const waits: Promise[] = [];
+ const event = new Event('sync') as Event & Record;
+ Object.assign(event, { tag: 'bulwark-outbox', waitUntil: (p: Promise) => waits.push(p) });
+ self.dispatchEvent(event);
+ await Promise.all(waits);
+ });
+ await expect.poll(async () => (await serverCopy(mail.id)).keywords.$seen === true, { timeout: 30_000 }).toBe(true);
+
+ // Offline mode stays local to this context, which ends here.
+ await context.close();
+ });
+});
+
+test.describe('with no tab open', () => {
+ let page: Page;
+ let context: BrowserContext;
+ let sw: Worker;
+
+ /** A blank tab keeps the context alive: it's outside the worker's scope. */
+ async function closeTheApp(): Promise {
+ const blank = await context.newPage();
+ await page.close();
+ await expect.poll(() => sw.evaluate(async () => (await (self as unknown as { clients: Clients }).clients.matchAll({ type: 'window', includeUncontrolled: true })).length)).toBe(0);
+ return blank;
+ }
+
+ test.beforeEach(async ({ browser }) => {
+ page = await userPage(browser, USER);
+ context = page.context();
+ await context.grantPermissions(['notifications']);
+ sw = await workerOf(context, page);
+ await expect.poll(() => sw.evaluate(async () => {
+ const cache = await caches.open('bulwark-push-state-v1');
+ return !!(await cache.match(`${self.location.origin}/__push-state/actions`));
+ }), { timeout: 30_000 }).toBe(true);
+ });
+
+ test.afterEach(async () => {
+ await context.close();
+ });
+
+ test('Mark read goes through the route on the context cookie', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await closeTheApp();
+ await routePosts(sw);
+ await click(sw, 'mark-read', shown.data);
+ expect((await routePosts(sw)).at(-1)).toContain('/api/push/action');
+ expect((await serverCopy(mail.id)).keywords.$seen).toBe(true);
+ expect(await opened(sw)).toEqual([]);
+ });
+
+ test('Archive goes through the route, to the folder the app uses', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await closeTheApp();
+ await click(sw, 'archive', shown.data);
+ const archive = await archiveFolderId();
+ expect(archive).toBeTruthy();
+ expect(Object.keys((await serverCopy(mail.id)).mailboxIds)).toEqual([archive]);
+ expect(await opened(sw)).toEqual([]);
+ });
+
+ test('Archive follows the mirrored mode into year and month folders', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await sw.evaluate(async () => {
+ const cache = await caches.open('bulwark-push-state-v1');
+ const key = `${self.location.origin}/__push-state/actions`;
+ const prefs = await (await cache.match(key))!.json();
+ await cache.put(key, new Response(JSON.stringify({ ...prefs, archiveMode: 'month' })));
+ });
+ await closeTheApp();
+ await click(sw, 'archive', shown.data);
+ const client = await jmapAs(USER);
+ const copy = await serverCopy(mail.id);
+ const [folderId] = Object.keys(copy.mailboxIds);
+ const folders = await client.mailboxes();
+ const month = folders.find((f) => f.id === folderId)!;
+ const year = folders.find((f) => f.id === month.parentId)!;
+ const when = new Date(copy.receivedAt);
+ expect(month.name).toBe(String(when.getMonth() + 1).padStart(2, '0'));
+ expect(year.name).toBe(String(when.getFullYear()));
+ expect(year.parentId).toBe(await archiveFolderId());
+ });
+
+ test('Archive makes the Archive, year and month folders on an account without them', async () => {
+ const client = await jmapAs(USER);
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await sw.evaluate(async () => {
+ const cache = await caches.open('bulwark-push-state-v1');
+ const key = `${self.location.origin}/__push-state/actions`;
+ const prefs = await (await cache.match(key))!.json();
+ await cache.put(key, new Response(JSON.stringify({ ...prefs, archiveMode: 'month' })));
+ });
+ await closeTheApp();
+ // Out of the way, so the account has no Archive for the moment.
+ const old = await client.mailboxByRole('archive');
+ const oldName = `Old archive ${RUN}`;
+ if (old) {
+ const renamed = await client.request([['Mailbox/set', { accountId: client.accountId, update: { [old.id]: { name: oldName, role: null } } }, 'r']]);
+ expect(renamed.methodResponses[0][1].updated).toHaveProperty(old.id);
+ }
+
+ await click(sw, 'archive', shown.data);
+
+ expect(await opened(sw)).toEqual([]);
+ const created = await client.mailboxByRole('archive');
+ expect(created?.name).toBe('Archive');
+ expect(created?.id).not.toBe(old?.id);
+ const copy = await serverCopy(mail.id);
+ const folders = await client.mailboxes();
+ const month = folders.find((f) => f.id === Object.keys(copy.mailboxIds)[0])!;
+ const year = folders.find((f) => f.id === month.parentId)!;
+ expect(year.parentId).toBe(created!.id);
+
+ if (old) {
+ // Only this spec's messages live in ent-dave's Archive.
+ await client.request([['Mailbox/set', { accountId: client.accountId, destroy: [old.id], onDestroyRemoveEmails: true }, 'd']]);
+ }
+ });
+
+ test('with an enabled plugin that may stop it, the route is skipped and the message opens', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await sw.evaluate(async () => {
+ const cache = await caches.open('bulwark-push-state-v1');
+ const key = `${self.location.origin}/__push-state/actions`;
+ const prefs = await (await cache.match(key))!.json();
+ await cache.put(key, new Response(JSON.stringify({ ...prefs, pluginsMayVeto: true })));
+ });
+ await closeTheApp();
+ await routePosts(sw);
+ await click(sw, 'mark-read', shown.data);
+ expect(await routePosts(sw)).toEqual([]);
+ expect((await opened(sw))[0]).toContain(`/mail/message/${mail.id}`);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ });
+
+ test('a message since moved to Trash stays there, and opens in the app', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await closeTheApp();
+ const client = await jmapAs(USER);
+ const trash = await client.mailboxByRole('trash');
+ await client.moveEmail(mail.id, trash!.id);
+ await click(sw, 'archive', shown.data);
+ expect((await opened(sw))[0]).toContain(`/mail/message/${mail.id}`);
+ expect(Object.keys((await serverCopy(mail.id)).mailboxIds)).toEqual([trash!.id]);
+ });
+
+ test('with the context cookie gone the message opens instead, and stays as it was', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await closeTheApp();
+ const jar = await context.cookies();
+ await context.clearCookies({ name: /^jmap_stalwart_ctx/ });
+ expect(jar.some((c) => c.name.startsWith('jmap_stalwart_ctx'))).toBe(true);
+ await routePosts(sw);
+ await click(sw, 'mark-read', shown.data);
+ expect((await routePosts(sw)).at(-1)).toContain('/api/push/action');
+ const urls = await opened(sw);
+ expect(urls).toHaveLength(1);
+ expect(urls[0]).toContain(`/mail/message/${mail.id}`);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ });
+
+ test('a notification from a login no longer signed in acts on nothing', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await closeTheApp();
+ await click(sw, 'mark-read', { ...shown.data, login: 'someone-else' });
+ expect(await opened(sw)).toHaveLength(1);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ });
+
+ test('Reply opens the link, the composer opens once with the typed text, and a reload leaves it shut', async () => {
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ const blank = await closeTheApp();
+ await click(sw, 'reply', shown.data, `Typed while closed ${RUN}`);
+ const [url] = await opened(sw);
+ expect(url).toContain(`/mail/message/${mail.id}`);
+ expect(url).toContain('reply=1');
+ expect(url).not.toContain('Typed');
+
+ page = await context.newPage();
+ await page.goto(url);
+ await blank.close();
+ const replyInput = () => page.evaluate((subjectText) => {
+ const inputs = [...document.querySelectorAll('input')] as HTMLInputElement[];
+ return inputs.some((input) => input.value === `Re: ${subjectText}`);
+ }, mail.subject);
+ await expect.poll(replyInput, { timeout: 45_000 }).toBe(true);
+ await expect(page.getByText(`Typed while closed ${RUN}`).first()).toBeVisible({ timeout: 10_000 });
+ expect(page.url()).not.toContain('reply=1');
+
+ // Leave the draft and come back: the link's job is done.
+ await page.reload();
+ await expect(page.getByText('Please answer.').first()).toBeVisible({ timeout: 45_000 });
+ expect(await replyInput()).toBe(false);
+ });
+});
+
+test.describe('Reply in the Pro shell', () => {
+ test('opens the composer in the message tab, with the typed text, from the live tab and from the link', async ({ browser }) => {
+ const page = await userPage(browser, USER);
+ const context = page.context();
+ await context.grantPermissions(['notifications']);
+ await page.evaluate(() => {
+ const raw = localStorage.getItem('settings-storage');
+ const stored = raw ? JSON.parse(raw) : { state: {} };
+ stored.state = { ...stored.state, proInterface: true };
+ localStorage.setItem('settings-storage', JSON.stringify(stored));
+ });
+ await page.goto('/pro');
+ await expect(page.locator('[data-pro-takeover]')).toHaveCount(0, { timeout: 60_000 });
+ const sw = await workerOf(context, page);
+ const replyIsOpen = (subject: string) => page.evaluate((text) => {
+ const inputs = [...document.querySelectorAll('input')] as HTMLInputElement[];
+ return inputs.some((input) => input.value === `Re: ${text}`);
+ }, subject);
+
+ const live = await oneUnread();
+ const liveShown = await pushed(sw, live.accountId, live.id);
+ // Until the shell's mail surface is up the tab declines, and the worker
+ // falls back to the link: ask again. Taken once, no window opens.
+ await expect.poll(async () => {
+ await click(sw, 'reply', liveShown.data, `Pro typed ${RUN}`);
+ return (await opened(sw)).length;
+ }, { timeout: 45_000, intervals: [3_000] }).toBe(0);
+ await expect.poll(() => replyIsOpen(live.subject), { timeout: 30_000 }).toBe(true);
+ await expect(page.getByText(`Pro typed ${RUN}`).first()).toBeVisible({ timeout: 10_000 });
+
+ const linked = await oneUnread();
+ await page.goto(`/mail/message/${linked.id}?owner=${linked.accountId}&reply=1`);
+ await expect.poll(() => replyIsOpen(linked.subject), { timeout: 60_000 }).toBe(true);
+ await context.close();
+ });
+});
+
+test.describe('session limits', () => {
+ test('under a maximum session age the route answers 401 and writes nothing', async ({ browser }) => {
+ const admin = await adminContext(browser);
+ const page = await userPage(browser, USER);
+ await page.context().grantPermissions(['notifications']);
+ const sw = await workerOf(page.context(), page);
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ await withPolicy(admin, { organisation: { session: { idleMinutes: 0, maxHours: 8, warnSeconds: 60 } } }, async () => {
+ const res = await page.request.post('/api/push/action', {
+ data: { action: 'mark-read', accountId: mail.accountId, emailId: mail.id, login: shown.data.login },
+ });
+ expect(res.status()).toBe(401);
+ });
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ await page.context().close();
+ await admin.close();
+ });
+});
+
+test.describe('the route, as a page or another site would call it', () => {
+ test('refuses a cross-site POST at the gate, with the cookies on it', async ({ browser }) => {
+ const page = await userPage(browser, USER);
+ const mail = await oneUnread();
+ const res = await page.request.post('/api/push/action', {
+ headers: { 'Sec-Fetch-Site': 'cross-site' },
+ data: { action: 'mark-read', accountId: mail.accountId, emailId: mail.id, login: 'x' },
+ });
+ expect(res.status()).toBe(403);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ await page.context().close();
+ });
+
+ test('refuses another account of the same login, and answers 401 without cookies', async ({ browser }) => {
+ const page = await userPage(browser, USER);
+ await page.context().grantPermissions(['notifications']);
+ const sw = await workerOf(page.context(), page);
+ const mail = await oneUnread();
+ const shown = await pushed(sw, mail.accountId, mail.id);
+ const post = (over: Record) => page.request.post('/api/push/action', {
+ data: { action: 'mark-read', accountId: mail.accountId, emailId: mail.id, login: shown.data.login, ...over },
+ });
+ expect((await post({ accountId: 'zzzzzz' })).status()).toBe(403);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ await page.context().clearCookies({ name: /^jmap_stalwart_ctx/ });
+ expect((await post({})).status()).toBe(401);
+ expect((await serverCopy(mail.id)).keywords.$seen).toBeFalsy();
+ await page.context().close();
+ });
+});
diff --git a/lib/__tests__/deep-links.test.ts b/lib/__tests__/deep-links.test.ts
index c9696f162..0dc59db84 100644
--- a/lib/__tests__/deep-links.test.ts
+++ b/lib/__tests__/deep-links.test.ts
@@ -185,6 +185,16 @@ describe('mail paths', () => {
expect(parseMailPath(['thread', 't1'])).toEqual({ kind: 'thread', id: 't1', accountId: undefined });
});
+ it("reads a notification's reply flag on a message link, and only there", () => {
+ expect(parseMailPath(['message', 'm1'], new URLSearchParams('slot=1&owner=a&reply=1'))).toMatchObject({
+ kind: 'message', id: 'm1', slot: 1, ownerAccountId: 'a', reply: true,
+ });
+ expect(parseMailPath(['message', 'm1'], new URLSearchParams('reply=0'))).not.toHaveProperty('reply');
+ expect(parseMailPath(['message', 'm1'])).not.toHaveProperty('reply');
+ expect(parseMailPath(['folder', 'inbox'], new URLSearchParams('reply=1'))).not.toHaveProperty('reply');
+ expect(parseMailPath(['thread', 't1'], new URLSearchParams('reply=1'))).not.toHaveProperty('reply');
+ });
+
it('reads the fullscreen marker on message links', () => {
expect(parseMailPath(['message', 'm1'], new URLSearchParams('view=fullscreen'))).toEqual({
kind: 'message',
diff --git a/lib/__tests__/launch-handoff.test.ts b/lib/__tests__/launch-handoff.test.ts
new file mode 100644
index 000000000..9dafa8f5d
--- /dev/null
+++ b/lib/__tests__/launch-handoff.test.ts
@@ -0,0 +1,526 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { FakeCaches, loadWorker } from './sw-harness';
+import {
+ HANDOFF_CACHE,
+ HANDOFF_MAX_BYTES,
+ HANDOFF_MAX_ENTRIES,
+ HANDOFF_TTL_MS,
+ adoptStoredHandoff,
+ clearHandoffs,
+ discardStoredHandoff,
+ expireHandoffs,
+ handOffDraft,
+ handOffFiles,
+ handOffLaunchFiles,
+ handOffNewMessage,
+ kindForFile,
+ parseLaunchLanding,
+ peekStoredHandoff,
+ pendingHandoffs,
+ restoreStoredHandoffs,
+ shareDraft,
+ shortcutFromTargetUrl,
+ stripLandingParams,
+ subscribeHandoff,
+ subscribeHandoffLost,
+ takeHandoff,
+} from '../launch-handoff';
+
+// Files and links from outside the app on their way to what handles them.
+
+const file = (name: string, type = '', body = 'x') => new File([body], name, { type });
+const handle = (f: File) => ({ kind: 'file', getFile: async () => f });
+// Sealing runs on Web Crypto's thread pool.
+const settle = () => new Promise((r) => setTimeout(r, 60));
+const whenStored = () => vi.waitFor(() => expect(sessionStorage.getItem('bulwark:launch-handoffs')).not.toBeNull(), { timeout: 5000 });
+
+function memoryStorage() {
+ const backing = new Map();
+ return {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => { backing.set(key, value); },
+ removeItem: (key: string) => { backing.delete(key); },
+ };
+}
+
+let caches: FakeCaches;
+
+beforeEach(() => {
+ caches = new FakeCaches();
+ vi.stubGlobal('caches', caches);
+ vi.stubGlobal('sessionStorage', memoryStorage());
+});
+
+afterEach(() => {
+ clearHandoffs();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('where a launched file goes', () => {
+ it.each([
+ ['mail.eml', '', 'eml'],
+ ['MAIL.EML', '', 'eml'],
+ ['invite.ics', '', 'calendar'],
+ ['invite.ical', '', 'calendar'],
+ ['people.vcf', '', 'contacts'],
+ ['people.vcard', '', 'contacts'],
+ ['noextension', 'message/rfc822', 'eml'],
+ ['noextension', 'text/calendar', 'calendar'],
+ ['noextension', 'text/x-vcard', 'contacts'],
+ ['photo.png', 'image/png', null],
+ ])('%s (%s) goes to %s', (name, type, kind) => {
+ expect(kindForFile(file(name, type))).toBe(kind);
+ });
+
+ it('splits one launch by type and names what nothing handles', async () => {
+ const eml = file('a.eml');
+ const ics = file('b.ics');
+ const vcf = file('c.vcf');
+ const result = await handOffLaunchFiles([handle(eml), handle(ics), handle(vcf), handle(file('d.png'))]);
+
+ expect(result).toEqual({ unsupported: ['d.png'], failed: 0 });
+ expect(takeHandoff('eml')?.files).toEqual([eml]);
+ expect(takeHandoff('calendar')?.files).toEqual([ics]);
+ expect(takeHandoff('contacts')?.files).toEqual([vcf]);
+ });
+
+ it('counts a file it could not read', async () => {
+ const result = await handOffLaunchFiles([{ kind: 'file', getFile: async () => { throw new Error('gone'); } }]);
+ expect(result).toEqual({ unsupported: [], failed: 1 });
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('skips a directory handle', async () => {
+ const result = await handOffLaunchFiles([{ kind: 'directory' }]);
+ expect(result).toEqual({ unsupported: [], failed: 0 });
+ expect(pendingHandoffs()).toEqual([]);
+ });
+});
+
+describe('handing off', () => {
+ it('gives a handoff to one taker, once', () => {
+ const ics = file('a.ics');
+ handOffFiles([ics], 'calendar');
+ expect(takeHandoff('contacts')).toBeNull();
+ expect(takeHandoff('calendar')?.files).toEqual([ics]);
+ expect(takeHandoff('calendar')).toBeNull();
+ });
+
+ it('tells the app first, while the handoff is still pending, then the taker', () => {
+ const order: string[] = [];
+ const offKind = subscribeHandoff('contacts', () => {
+ order.push(`taker:${takeHandoff('contacts') ? 'got it' : 'nothing'}`);
+ });
+ const offAny = subscribeHandoff('any', (kind) => {
+ order.push(`app:${kind}:${pendingHandoffs().length}`);
+ });
+ handOffFiles([file('a.vcf')], 'contacts');
+ expect(order).toEqual(['app:contacts:1', 'taker:got it']);
+ offKind();
+ offAny();
+ });
+
+ it('stops telling a listener that unsubscribed', () => {
+ const listener = vi.fn();
+ subscribeHandoff('calendar', listener)();
+ handOffFiles([file('a.ics')], 'calendar');
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for no files', () => {
+ handOffFiles([], 'calendar');
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('drops what waited too long', () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ handOffFiles([file('a.ics')], 'calendar');
+ vi.advanceTimersByTime(HANDOFF_TTL_MS + 1);
+ expect(takeHandoff('calendar')).toBeNull();
+ expect(pendingHandoffs()).toEqual([]);
+ });
+
+ it('counts a new message that arrives twice in one launch once', () => {
+ handOffNewMessage();
+ handOffNewMessage();
+ expect(takeHandoff('compose')).toMatchObject({ files: [] });
+ expect(takeHandoff('compose')).toBeNull();
+ });
+
+ it('carries the text of a draft', () => {
+ handOffDraft({ subject: 'Hi', body: 'There', files: [file('a.pdf')] });
+ const handoff = takeHandoff('compose');
+ expect(handoff).toMatchObject({ subject: 'Hi', body: 'There' });
+ expect(handoff?.files.map((f) => f.name)).toEqual(['a.pdf']);
+ });
+});
+
+describe('across a page load', () => {
+ // A sign-in through SSO leaves the page. A new module state stands in for
+ // the new page: the queue is emptied, sessionStorage and the cache stay.
+ async function newPage() {
+ pendingHandoffs();
+ while (takeHandoffQuietly()) { /* the old page's memory goes */ }
+ }
+ function takeHandoffQuietly() {
+ const list = pendingHandoffs() as unknown as unknown[];
+ return list.length > 0 ? list.splice(0, list.length) : null;
+ }
+
+ it('brings back a file that waited for a sign-in, with its name and type', async () => {
+ handOffFiles([file('a.ics', 'text/calendar', 'BEGIN:VCALENDAR')], 'calendar');
+ await whenStored();
+ await newPage();
+ expect(takeHandoff('calendar')).toBeNull();
+
+ await restoreStoredHandoffs();
+ const handoff = takeHandoff('calendar');
+ expect(handoff?.files[0].name).toBe('a.ics');
+ expect(handoff?.files[0].type).toBe('text/calendar');
+ expect(await handoff?.files[0].text()).toBe('BEGIN:VCALENDAR');
+ });
+
+ it('removes the stored copy once it is taken', async () => {
+ handOffFiles([file('a.ics')], 'calendar');
+ await whenStored();
+ const store = await caches.open(HANDOFF_CACHE);
+ expect((await store.keys()).length).toBe(3);
+
+ takeHandoff('calendar');
+ await settle();
+ await settle();
+ expect((await store.keys()).length).toBe(0);
+ expect(sessionStorage.getItem('bulwark:launch-handoffs')).toBeNull();
+ });
+
+ it('never stores a .eml: it opens at once and needs no sign-in', async () => {
+ handOffFiles([file('a.eml')], 'eml');
+ await settle();
+ expect(await caches.has(HANDOFF_CACHE)).toBe(false);
+ });
+
+ it("leaves another window's handoff alone", async () => {
+ handOffFiles([file('a.ics')], 'calendar');
+ await whenStored();
+ await newPage();
+ // Another window: its own sessionStorage, the same cache.
+ vi.stubGlobal('sessionStorage', memoryStorage());
+ await restoreStoredHandoffs();
+ expect(takeHandoff('calendar')).toBeNull();
+ expect((await (await caches.open(HANDOFF_CACHE)).keys()).length).toBe(3);
+ });
+
+ it('keeps no readable bytes, name or text at rest', async () => {
+ handOffDraft({ subject: 'Secret subject', body: 'Secret text', files: [file('secret-name.txt', 'text/plain', 'secret bytes')] });
+ await whenStored();
+ const store = await caches.open(HANDOFF_CACHE);
+ const keys = await store.keys();
+ expect(keys.length).toBeGreaterThanOrEqual(3);
+ for (const key of keys) {
+ const stored = await (await store.match(key))!.text();
+ for (const secret of ['Secret subject', 'Secret text', 'secret-name', 'secret bytes']) expect(stored).not.toContain(secret);
+ }
+ });
+
+ it('cannot read it once the tab with the key is gone', async () => {
+ handOffFiles([file('a.ics')], 'calendar');
+ await whenStored();
+ await newPage();
+ vi.stubGlobal('sessionStorage', memoryStorage());
+ const store = await caches.open(HANDOFF_CACHE);
+ const metaKey = (await store.keys()).find((key) => key.url.endsWith('/meta'))!.url;
+ const id = metaKey.split('/').slice(-2)[0];
+ expect(await adoptStoredHandoff(id)).toBe(false);
+ expect(await adoptStoredHandoff(id, 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')).toBe(false);
+ });
+
+ it('says so when a stored handoff of this tab is gone after the reload', async () => {
+ const losses: string[] = [];
+ const off = subscribeHandoffLost((loss) => losses.push(loss));
+ handOffFiles([file('a.ics')], 'calendar');
+ await whenStored();
+ await newPage();
+ await caches.delete(HANDOFF_CACHE);
+ await restoreStoredHandoffs();
+ expect(losses).toEqual(['expired']);
+ expect(sessionStorage.getItem('bulwark:launch-handoffs')).toBeNull();
+ off();
+ });
+
+ it('says so when a stored file is missing, and delivers the rest', async () => {
+ const losses: string[] = [];
+ const off = subscribeHandoffLost((loss) => losses.push(loss));
+ handOffDraft({ subject: 'S', files: [file('one.txt'), file('two.txt')] });
+ await whenStored();
+ await newPage();
+ const store = await caches.open(HANDOFF_CACHE);
+ const first = (await store.keys()).find((key) => key.url.endsWith('/0'))!;
+ await store.delete(first);
+ await restoreStoredHandoffs();
+ expect(losses).toEqual(['missing']);
+ expect(takeHandoff('compose')?.files.map((f) => f.name)).toEqual(['two.txt']);
+ off();
+ });
+
+ it('keeps no more than the limit, oldest out first', async () => {
+ const created: string[] = [];
+ for (let n = 0; n < HANDOFF_MAX_ENTRIES + 2; n += 1) {
+ const name = `f${n}.ics`;
+ handOffFiles([file(name)], 'calendar');
+ created.push(name);
+ await settle();
+ await settle();
+ }
+ const store = await caches.open(HANDOFF_CACHE);
+ const metas = (await store.keys()).filter((key) => key.url.endsWith('/meta'));
+ expect(metas.length).toBeLessThanOrEqual(HANDOFF_MAX_ENTRIES);
+ });
+
+ it('does not store what is over the byte limit, and keeps it in memory', async () => {
+ const big = file('big.ics');
+ Object.defineProperty(big, 'size', { value: HANDOFF_MAX_BYTES + 1 });
+ handOffFiles([big], 'calendar');
+ await settle();
+ expect(await caches.has(HANDOFF_CACHE)).toBe(false);
+ expect(takeHandoff('calendar')?.files).toEqual([big]);
+ });
+
+ it('sweeps what nobody took, and keeps what is recent', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ handOffFiles([file('old.ics')], 'calendar');
+ await whenStored();
+ await newPage();
+ vi.stubGlobal('sessionStorage', memoryStorage());
+ vi.advanceTimersByTime(HANDOFF_TTL_MS + 1);
+ handOffFiles([file('new.vcf')], 'contacts');
+ await whenStored();
+
+ await restoreStoredHandoffs();
+ const store = await caches.open(HANDOFF_CACHE);
+ const urls = (await store.keys()).map((key) => key.url);
+ expect(urls).toHaveLength(3);
+ const meta = await store.match(urls.find((url) => url.endsWith('/meta'))!);
+ expect(((await meta!.json()) as { kind: string }).kind).toBe('contacts');
+ });
+
+ it('keeps working in memory without the Cache API', async () => {
+ vi.stubGlobal('caches', undefined);
+ const ics = file('a.ics');
+ handOffFiles([ics], 'calendar');
+ await settle();
+ expect(takeHandoff('calendar')?.files).toEqual([ics]);
+ expect(await adoptStoredHandoff('anything')).toBe(false);
+ });
+
+ it('keeps the file in memory when the cache is full', async () => {
+ const original = caches.open.bind(caches);
+ vi.spyOn(caches, 'open').mockImplementation(async (name: string) => ({
+ ...(await original(name)),
+ put: async () => { throw new DOMException('full', 'QuotaExceededError'); },
+ }));
+ const ics = file('a.ics');
+ handOffFiles([ics], 'calendar');
+ await settle();
+ expect(sessionStorage.getItem('bulwark:launch-handoffs')).toBeNull();
+ expect(takeHandoff('calendar')?.files).toEqual([ics]);
+ });
+});
+
+describe('while the page stays open', () => {
+ it('drops what waited too long on a timer, and says so', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
+ const losses: string[] = [];
+ const off = subscribeHandoffLost((loss) => losses.push(loss));
+ handOffFiles([file('a.eml')], 'eml');
+ await vi.advanceTimersByTimeAsync(HANDOFF_TTL_MS + 2000);
+ expect(pendingHandoffs()).toEqual([]);
+ expect(losses).toEqual(['expired']);
+ off();
+ });
+
+ it('says so when a taker finds only an expired handoff', () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ const losses: string[] = [];
+ const off = subscribeHandoffLost((loss) => losses.push(loss));
+ handOffFiles([file('a.eml')], 'eml');
+ vi.advanceTimersByTime(HANDOFF_TTL_MS + 1);
+ expect(takeHandoff('eml')).toBeNull();
+ expect(losses).toEqual(['expired']);
+ off();
+ });
+
+ it('keeps what is still in time', async () => {
+ handOffFiles([file('a.eml')], 'eml');
+ await expireHandoffs();
+ expect(pendingHandoffs()).toHaveLength(1);
+ });
+
+ it('leaves the second of two drafts queued until it is taken', () => {
+ handOffDraft({ subject: 'first' });
+ handOffDraft({ subject: 'second' });
+ expect(takeHandoff('compose')?.subject).toBe('first');
+ expect(pendingHandoffs().map((h) => h.subject)).toEqual(['second']);
+ });
+});
+
+describe('sign-out', () => {
+ it('forgets what is waiting, in memory and stored', async () => {
+ handOffFiles([file('a.ics')], 'calendar');
+ await whenStored();
+ clearHandoffs();
+ await settle();
+ expect(pendingHandoffs()).toEqual([]);
+ expect(await caches.has(HANDOFF_CACHE)).toBe(false);
+ expect(sessionStorage.getItem('bulwark:launch-handoffs')).toBeNull();
+ });
+});
+
+describe('what the service worker stored', () => {
+ it('becomes a draft with the files, under the id in the address', async () => {
+ // The real worker writes it, so this fails if the two layouts drift apart.
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const form = new FormData();
+ form.set('title', 'A link');
+ form.set('text', 'Look at this');
+ form.set('url', 'https://example.org/page');
+ form.append('files', file('photo.png', 'image/png', 'bytes'));
+ const answer = await worker.request({ url: 'https://mail.example.com/protocol/share', method: 'POST', mode: 'navigate', destination: 'document', formData: async () => form } as never);
+ const location = new URL(answer!.headers.get('location')!);
+ const landing = parseLaunchLanding(location.search, location.hash);
+ expect(landing?.type).toBe('stored');
+ const { id, key } = landing as { id: string; key: string };
+
+ // Without the key from the address it can't be read; asking shows what it is.
+ expect(await peekStoredHandoff(id, '')).toBeNull();
+ expect(await peekStoredHandoff(id, key)).toEqual({ subject: 'A link', body: 'Look at this\n\nhttps://example.org/page', files: ['photo.png'] });
+ expect(pendingHandoffs()).toEqual([]);
+
+ expect(await adoptStoredHandoff(id, key)).toBe(true);
+ const handoff = takeHandoff('compose');
+ expect(handoff).toMatchObject({ subject: 'A link', body: 'Look at this\n\nhttps://example.org/page' });
+ expect(handoff?.files[0].name).toBe('photo.png');
+ expect(handoff?.files[0].type).toBe('image/png');
+ expect(await handoff?.files[0].text()).toBe('bytes');
+ await settle();
+ await settle();
+ expect((await (await caches.open(HANDOFF_CACHE)).keys()).length).toBe(0);
+ });
+
+ it('is gone when the id names nothing', async () => {
+ expect(await adoptStoredHandoff('11111111-2222', 'AAAA')).toBe(false);
+ expect(await peekStoredHandoff('11111111-2222', 'AAAA')).toBeNull();
+ });
+
+ it('goes when the user refuses it', async () => {
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const form = new FormData();
+ form.append('files', file('photo.png'));
+ const answer = await worker.request({ url: 'https://mail.example.com/protocol/share', method: 'POST', mode: 'navigate', destination: 'document', formData: async () => form } as never);
+ const location = new URL(answer!.headers.get('location')!);
+ const { id, key } = parseLaunchLanding(location.search, location.hash) as { id: string; key: string };
+ await discardStoredHandoff(id);
+ expect((await (await caches.open(HANDOFF_CACHE)).keys()).length).toBe(0);
+ expect(await peekStoredHandoff(id, key)).toBeNull();
+ });
+
+ it('cleans control characters out of names and text, as for a mailto: link', async () => {
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const form = new FormData();
+ form.set('title', 'Hi\r\nBcc: evil@example.org');
+ form.append('files', file('a\u202Egnp.exe'));
+ const answer = await worker.request({ url: 'https://mail.example.com/protocol/share', method: 'POST', mode: 'navigate', destination: 'document', formData: async () => form } as never);
+ const location = new URL(answer!.headers.get('location')!);
+ const { id, key } = parseLaunchLanding(location.search, location.hash) as { id: string; key: string };
+ expect(await peekStoredHandoff(id, key)).toMatchObject({ subject: 'HiBcc: evil@example.org', files: ['agnp.exe'] });
+ });
+
+ it('is gone when it is too old', async () => {
+ const store = await caches.open(HANDOFF_CACHE);
+ await store.put('/__bulwark/handoff/old/meta', new Response(JSON.stringify({ kind: 'compose', createdAt: Date.now() - HANDOFF_TTL_MS - 1, bytes: 0 })));
+ expect(await adoptStoredHandoff('old', 'AAAA')).toBe(false);
+ expect((await store.keys()).length).toBe(0);
+ });
+});
+
+describe('text of a share', () => {
+ it('puts the link under the text', () => {
+ expect(shareDraft({ title: ' T ', text: 'Hello', url: 'https://a.example' })).toEqual({ subject: 'T', body: 'Hello\n\nhttps://a.example' });
+ });
+
+ it('does not repeat a link that is in the text already', () => {
+ expect(shareDraft({ text: 'See https://a.example now', url: 'https://a.example' }).body).toBe('See https://a.example now');
+ });
+
+ it('copes with only a link', () => {
+ expect(shareDraft({ url: 'https://a.example' })).toEqual({ subject: '', body: 'https://a.example' });
+ });
+
+ it('strips control characters from the subject, so no header can be planted', () => {
+ expect(shareDraft({ title: 'Hi\r\nBcc: evil@example.org' }).subject).toBe('HiBcc: evil@example.org');
+ });
+
+ it('keeps line breaks in the body and drops other control characters', () => {
+ expect(shareDraft({ text: 'one\r\ntwo\u0000\u0007' }).body).toBe('one\ntwo');
+ });
+
+ it('applies the limits of a mailto: link', () => {
+ const draft = shareDraft({ title: 'x'.repeat(2000), text: 'y'.repeat(100_000), url: 'https://a.example' });
+ expect(draft.subject).toHaveLength(998);
+ expect(draft.body).toHaveLength(64 * 1024);
+ });
+
+ it('applies them to a draft handed in directly as well', () => {
+ handOffDraft({ subject: 'a\r\nb', body: 'y'.repeat(100_000) });
+ const handoff = takeHandoff('compose');
+ expect(handoff?.subject).toBe('ab');
+ expect(handoff?.body).toHaveLength(64 * 1024);
+ });
+});
+
+describe('the address a launch lands on', () => {
+ it.each([
+ ['?compose=1', '', { type: 'new-message' }],
+ ['', '#share=abc-123&key=k1', { type: 'stored', id: 'abc-123', key: 'k1' }],
+ ['', '#share=unavailable&share_title=T&share_text=B&share_files=1', { type: 'inline', subject: 'T', body: 'B', filesLost: true, cut: false }],
+ ['', '#share=unavailable&share_url=https%3A%2F%2Fa.example&share_cut=1', { type: 'inline', subject: '', body: 'https://a.example', filesLost: false, cut: true }],
+ ['', '#share=..%2F..%2Fetc', null],
+ // Shared text stays out of the query, which reaches logs.
+ ['?share=unavailable&share_text=x', '', null],
+ ['?compose=0', '', null],
+ ['?openLatestUnread=1', '#x', null],
+ ['', '', null],
+ ])('%s %s', (search, hash, expected) => {
+ expect(parseLaunchLanding(search, hash)).toEqual(expected);
+ });
+
+ it('cleans text that came in the address', () => {
+ const landing = parseLaunchLanding('', '#share=unavailable&share_title=Hi%0D%0ABcc%3A%20evil');
+ expect(landing).toMatchObject({ subject: 'HiBcc: evil' });
+ });
+
+ it('leaves only what is not about the launch', () => {
+ expect(stripLandingParams('?compose=1', '')).toEqual({ search: '', hash: '' });
+ expect(stripLandingParams('?slot=2', '#share=unavailable&share_text=x')).toEqual({ search: '?slot=2', hash: '' });
+ expect(stripLandingParams('?compose=1&slot=2', '#section')).toEqual({ search: '?slot=2', hash: '#section' });
+ expect(stripLandingParams('', '#share=a&key=b')).toEqual({ search: '', hash: '' });
+ });
+});
+
+describe('a shortcut reaching an open window', () => {
+ const origin = 'https://mail.example.com';
+ it.each([
+ [`${origin}/?compose=1`, 'new-message'],
+ [`${origin}/en/?compose=1`, 'new-message'],
+ [`${origin}/calendar`, 'calendar'],
+ [`${origin}/de/contacts`, 'contacts'],
+ // The plain app icon and links into the app don't move an open window.
+ [`${origin}/`, null],
+ [`${origin}/calendar/some-event`, null],
+ [`${origin}/settings`, null],
+ ['https://evil.example/calendar', null],
+ ])('%s', (target, expected) => {
+ expect(shortcutFromTargetUrl(target, origin)).toBe(expected);
+ });
+});
diff --git a/lib/__tests__/manifest-launch.test.ts b/lib/__tests__/manifest-launch.test.ts
new file mode 100644
index 000000000..c4c2794f4
--- /dev/null
+++ b/lib/__tests__/manifest-launch.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment node
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Shortcuts, file handlers and the share target in the manifest, with what
+// the route already did (per-domain branding, the deployment subpath).
+
+const hoisted = vi.hoisted(() => ({
+ requestHeaders: {} as Record,
+ config: {} as Record,
+ sources: {} as Record,
+}));
+
+vi.mock('next/headers', () => ({
+ headers: async () => new Headers(hoisted.requestHeaders),
+}));
+
+// The real strings, so a missing or misnamed key fails here.
+vi.mock('next-intl/server', () => ({
+ getTranslations: async ({ locale, namespace }: { locale: string; namespace: string }) => {
+ const messages = JSON.parse(readFileSync(join(process.cwd(), 'locales', locale, 'common.json'), 'utf8'));
+ return (key: string) => {
+ const value = messages[namespace]?.[key];
+ if (typeof value !== 'string') throw new Error(`missing ${namespace}.${key} in ${locale}`);
+ return value;
+ };
+ },
+}));
+
+vi.mock('@/lib/admin/config-manager', () => ({
+ configManager: {
+ ensureLoaded: async () => {},
+ get: (key: string, fallback: unknown) => hoisted.config[key] ?? fallback,
+ getAllWithSources: () => hoisted.sources,
+ },
+}));
+
+type Manifest = {
+ name: string;
+ shortcuts: Array<{ name: string; url: string; icons: Array<{ src: string }> }>;
+ file_handlers: Array<{ action: string; accept: Record }>;
+ share_target: { action: string; method: string; enctype: string; params: Record };
+ protocol_handlers: Array<{ protocol: string; url: string }>;
+};
+
+async function load(): Promise {
+ vi.resetModules();
+ const { default: manifest } = await import('@/app/manifest');
+ return (await manifest()) as unknown as Manifest;
+}
+
+beforeEach(() => {
+ hoisted.requestHeaders = {};
+ hoisted.config = {};
+ hoisted.sources = {
+ pwaIconUrl: { source: 'default' },
+ faviconUrl: { source: 'default' },
+ pwaScreenshotMobileUrl: { source: 'default' },
+ pwaScreenshotDesktopUrl: { source: 'default' },
+ };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('manifest launch fields', () => {
+ it('offers the three shortcuts', async () => {
+ const m = await load();
+ expect(m.shortcuts.map((s) => [s.name, s.url])).toEqual([
+ ['New message', '/?compose=1'],
+ ['Calendar', '/calendar'],
+ ['Contacts', '/contacts'],
+ ]);
+ });
+
+ it('names the shortcuts in the language the browser asks in', async () => {
+ hoisted.requestHeaders = { 'accept-language': 'de-DE,de;q=0.9,en;q=0.8' };
+ expect((await load()).shortcuts.map((s) => s.name)).toEqual(['Neue Nachricht', 'Kalender', 'Kontakte']);
+ });
+
+ it('falls back to English for a language it does not have', async () => {
+ hoisted.requestHeaders = { 'accept-language': 'xx' };
+ expect((await load()).shortcuts[0].name).toBe('New message');
+ });
+
+ it('handles .eml, .ics and .vcf', async () => {
+ const m = await load();
+ const extensions = (action: string) => Object.values(m.file_handlers.find((h) => h.action === action)?.accept ?? {}).flat();
+ expect(extensions('/mail')).toEqual(['.eml']);
+ expect(extensions('/calendar')).toEqual(expect.arrayContaining(['.ics']));
+ expect(extensions('/contacts')).toEqual(expect.arrayContaining(['.vcf']));
+ expect(m.file_handlers).toHaveLength(3);
+ });
+
+ it('takes shares as multipart POST outside /api/, with files and links', async () => {
+ const { share_target: share } = await load();
+ expect(share.action).toBe('/protocol/share');
+ expect(share.action.startsWith('/api/')).toBe(false);
+ expect(share.method).toBe('POST');
+ expect(share.enctype).toBe('multipart/form-data');
+ expect(share.params).toEqual({ title: 'title', text: 'text', url: 'url', files: [{ name: 'files', accept: ['*/*'] }] });
+ });
+
+ it('prefixes every new address with the subpath', async () => {
+ vi.stubEnv('NEXT_PUBLIC_BASE_PATH', '/webmail');
+ const m = await load();
+ expect(m.shortcuts.map((s) => s.url)).toEqual(['/webmail/?compose=1', '/webmail/calendar', '/webmail/contacts']);
+ expect(m.shortcuts[0].icons[0].src).toBe('/webmail/icon-192x192.png');
+ expect(m.file_handlers.map((h) => h.action)).toEqual(['/webmail/mail', '/webmail/calendar', '/webmail/contacts']);
+ expect(m.share_target.action).toBe('/webmail/protocol/share');
+ });
+
+ it("keeps a domain's branding, its icon on the shortcuts too", async () => {
+ hoisted.requestHeaders = { host: 'mail.acme.example' };
+ hoisted.config = { domainBranding: [{ host: 'mail.acme.example', appName: 'Acme Mail', pwaIconUrl: 'https://cdn.example/i.png' }] };
+ const m = await load();
+ expect(m.name).toBe('Acme Mail');
+ expect(m.shortcuts[0].icons[0].src).toBe('/api/pwa-icon/192');
+ expect(m.file_handlers).toHaveLength(3);
+ expect(m.share_target.action).toBe('/protocol/share');
+ });
+
+ it('leaves the protocol handlers as they are', async () => {
+ expect((await load()).protocol_handlers.map((h) => h.url)).toEqual(['/protocol/mailto?url=%s', '/protocol/webcal?url=%s']);
+ });
+});
+
+describe('Lite', () => {
+ it('has no share target or file handlers: no service worker, no launch consumer behind them', async () => {
+ const { buildManifest } = await import('@/scripts/lite/lib.mjs');
+ const lite = buildManifest({ appName: 'Acme' });
+ expect(lite).not.toHaveProperty('share_target');
+ expect(lite).not.toHaveProperty('file_handlers');
+ expect(lite).not.toHaveProperty('shortcuts');
+ });
+});
+
+describe('share route without a service worker', () => {
+ const route = () => import('@/app/(main)/protocol/share/route');
+
+ function post(form: FormData | null, contentLength?: string) {
+ const request = new Request('https://mail.example.com/protocol/share', { method: 'POST', ...(form ? { body: form } : {}) });
+ if (contentLength !== undefined) {
+ const headers = new Headers(request.headers);
+ headers.set('content-length', contentLength);
+ return { headers, formData: () => request.formData() } as unknown as Request;
+ }
+ return request;
+ }
+
+ it('sends text and links on to a new draft, and goes to the app with a 303', async () => {
+ const { POST } = await route();
+ const form = new FormData();
+ form.set('title', 'T');
+ form.set('text', 'B');
+ form.set('url', 'https://example.org/');
+ const res = await POST(post(form, '500'));
+ expect(res.status).toBe(303);
+ const landing = new URL(res.headers.get('location')!, 'https://x.example');
+ expect(landing.pathname).toBe('/');
+ // In the fragment: it never reaches an access log.
+ expect(landing.search).toBe('');
+ expect(Object.fromEntries(new URLSearchParams(landing.hash.slice(1)))).toEqual({ share: 'unavailable', share_title: 'T', share_text: 'B', share_url: 'https://example.org/' });
+ });
+
+ it('says files were lost', async () => {
+ const { POST } = await route();
+ const form = new FormData();
+ form.set('text', 'B');
+ form.append('files', new File(['x'], 'a.png'));
+ const res = await POST(post(form, '500'));
+ expect(res.headers.get('location')).toContain('share_files=1');
+ });
+
+ it('does not read a large upload into memory', async () => {
+ const { POST } = await route();
+ const form = new FormData();
+ form.set('text', 'B');
+ const spy = vi.fn(async () => form);
+ const request = { headers: new Headers({ 'content-length': String(50 * 1024 * 1024) }), formData: spy } as unknown as Request;
+ const res = await POST(request);
+ expect(spy).not.toHaveBeenCalled();
+ expect(res.headers.get('location')).toContain('share_files=1');
+ });
+
+ it.each([
+ ['Latin', 'x'],
+ ['Japanese, 9 encoded bytes each', 'あ'],
+ ['emoji, whole characters only', '😀'],
+ ])('keeps the address short and says it cut: %s', async (_name, character) => {
+ const { POST } = await route();
+ const form = new FormData();
+ form.set('text', character.repeat(3000));
+ form.set('title', character.repeat(3000));
+ form.set('url', character.repeat(3000));
+ const res = await POST(post(form, '100000'));
+ const location = res.headers.get('location')!;
+ expect(location.length).toBeLessThan(4000);
+ const fragment = new URLSearchParams(new URL(location, 'https://x.example').hash.slice(1));
+ expect(fragment.get('share_cut')).toBe('1');
+ // Decodes cleanly: no half a character at the end.
+ expect(fragment.get('share_text')!.endsWith(character)).toBe(true);
+ });
+
+ it('does not say it cut what fits', async () => {
+ const { POST } = await route();
+ const form = new FormData();
+ form.set('text', 'あ'.repeat(100));
+ const res = await POST(post(form, '1000'));
+ expect(res.headers.get('location')).not.toContain('share_cut');
+ });
+
+ it('honours the subpath', async () => {
+ vi.stubEnv('NEXT_PUBLIC_BASE_PATH', '/webmail');
+ vi.resetModules();
+ const { GET } = await route();
+ expect(GET().headers.get('location')).toBe('/webmail/');
+ });
+});
diff --git a/lib/__tests__/plugin-post-denylist.test.ts b/lib/__tests__/plugin-post-denylist.test.ts
index 5d0fad219..1c266ee1b 100644
--- a/lib/__tests__/plugin-post-denylist.test.ts
+++ b/lib/__tests__/plugin-post-denylist.test.ts
@@ -29,6 +29,7 @@ describe('routes no plugin may POST to', () => {
'/api/%70lugin-proxy',
'/api//plugin-secrets',
'/api/account/stalwart/jmap',
+ '/api/push/action',
])('%s is denied', (path) => {
expect(isPluginPostDenied(path)).toBe(true);
});
diff --git a/lib/__tests__/push-action-route.test.ts b/lib/__tests__/push-action-route.test.ts
new file mode 100644
index 000000000..c120db3d0
--- /dev/null
+++ b/lib/__tests__/push-action-route.test.ts
@@ -0,0 +1,428 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { NextRequest } from 'next/server';
+import { loginFingerprint } from '@/lib/pwa-notify/login-fingerprint';
+
+// POST /api/push/action: a notification's Mark read and Archive with no tab
+// open. Every refusal must leave the mail alone: the worker opens the message
+// in the app instead.
+
+vi.mock('next/headers', () => ({ cookies: async () => ({ get: () => undefined }) }));
+vi.mock('@/lib/logger', () => ({ logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() } }));
+vi.mock('@/lib/account-utils', () => ({ MAX_ACCOUNT_SLOTS: 3 }));
+
+type Login = { serverUrl: string; username: string; authHeader: string };
+let LOGINS: Array = [];
+vi.mock('@/lib/stalwart/auth-context', () => ({
+ readStalwartAuthContextFromStore: (_store: unknown, slot: number) => LOGINS[slot] ?? null,
+}));
+
+const ALICE: Login = { serverUrl: 'https://one.example/', username: 'alice@example.org', authHeader: 'Bearer alice' };
+const BOB: Login = { serverUrl: 'https://one.example', username: 'bob@example.org', authHeader: 'Bearer bob' };
+
+let policy: Record = {};
+vi.mock('@/lib/admin/config-manager', () => ({
+ configManager: { ensureLoaded: async () => {}, getPolicy: () => policy },
+}));
+let subject: { email: string; groups: string[] } | null = { email: 'alice@example.org', groups: [] };
+vi.mock('@/lib/admin/server-device-policy', () => ({ strictDeviceSubject: async () => subject }));
+
+type Calls = Array<[string, Record, string]>;
+const writes: Array<{ auth: string; url: string; calls: Calls }> = [];
+let session: Record;
+let sessionStatus = 200;
+let mailboxes: Array>;
+let email: Record | null;
+let emailSetResult: Record | null = null;
+// The answer to each Mailbox/set in turn; `undefined`: everything was created.
+let mailboxSetResults: Array> = [];
+let mailboxReads = 0;
+let mailboxesOnSecondRead: Array> | null = null;
+let emailSetResults: Array> = [];
+let sessionsAsked = 0;
+
+const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
+vi.mock('@/lib/stalwart/server-fetch', () => ({
+ isTrustedJmapServerUrl: async () => true,
+ fetchJmapServer: async (url: string, init?: { headers?: Record; body?: string }) => {
+ if (url.endsWith('/.well-known/jmap')) {
+ sessionsAsked++;
+ return sessionStatus === 200 ? json(session) : new Response('', { status: sessionStatus });
+ }
+ const calls = (JSON.parse(init?.body ?? '{}') as { methodCalls: Calls }).methodCalls;
+ if (calls.some(([name]) => name.endsWith('/set'))) {
+ writes.push({ auth: init?.headers?.Authorization ?? '', url, calls });
+ }
+ return json({
+ methodResponses: calls.map(([name, args, id]) => {
+ if (name === 'Mailbox/get') {
+ mailboxReads++;
+ return [name, { list: mailboxReads >= 2 && mailboxesOnSecondRead ? mailboxesOnSecondRead : mailboxes }, id];
+ }
+ if (name === 'Email/get') return [name, { list: email ? [email] : [] }, id];
+ if (name === 'Mailbox/set') {
+ if (args.destroy) return [name, { destroyed: args.destroy }, id];
+ return [name, mailboxSetResults.shift() ?? {
+ created: Object.fromEntries(Object.keys(args.create as object).map((cid) => [cid, { id: `new-${cid}` }])),
+ }, id];
+ }
+ const emailId = Object.keys(args.update as Record)[0];
+ return [name, emailSetResults.shift() ?? emailSetResult ?? { updated: { [emailId]: null } }, id];
+ }),
+ });
+ },
+}));
+
+const INBOX = { id: 'inbox', name: 'Inbox', role: 'inbox' };
+const ARCHIVE = { id: 'arch', name: 'Archive', role: 'archive' };
+
+async function call(body: Record, headers: Record = { 'sec-fetch-site': 'same-origin' }) {
+ const { POST } = await import('@/app/api/push/action/route');
+ const res = await POST(new NextRequest('https://mail.example.com/api/push/action', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ }));
+ return { status: res.status, body: await res.json() };
+}
+
+const fingerprint = (login: Login) => loginFingerprint(login.serverUrl, login.username);
+const destroyed = () => writes.flatMap((w) => w.calls).find(([name, args]) => name === 'Mailbox/set' && args.destroy)?.[1].destroy;
+const markRead = async (over: Record = {}) => ({
+ action: 'mark-read', accountId: 'a', emailId: 'e1', login: await fingerprint(ALICE), ...over,
+});
+const archive = async (over: Record = {}) => ({ ...(await markRead()), action: 'archive', ...over });
+const emailSet = () => {
+ const call = writes.at(-1)!.calls.find(([name]) => name === 'Email/set');
+ return call?.[1] as { accountId: string; update: Record> };
+};
+const mailboxSet = () => writes[0].calls.find(([name]) => name === 'Mailbox/set')?.[1] as { create: Record> } | undefined;
+
+beforeEach(() => {
+ LOGINS = [ALICE];
+ policy = {};
+ subject = { email: 'alice@example.org', groups: [] };
+ writes.length = 0;
+ sessionsAsked = 0;
+ sessionStatus = 200;
+ session = {
+ apiUrl: 'https://one.example/jmap/',
+ primaryAccounts: { 'urn:ietf:params:jmap:mail': 'a' },
+ accounts: { a: { name: 'alice@example.org', accountCapabilities: { 'urn:ietf:params:jmap:mail': {} } } },
+ };
+ mailboxes = [INBOX, ARCHIVE];
+ email = { id: 'e1', receivedAt: '2026-03-31T23:30:00Z', mailboxIds: { inbox: true } };
+ emailSetResult = null;
+ mailboxSetResults = [];
+ mailboxReads = 0;
+ mailboxesOnSecondRead = null;
+ emailSetResults = [];
+});
+
+describe('who may ask', () => {
+ it('refuses a request from another site before reading anything', async () => {
+ const res = await call(await markRead(), { 'sec-fetch-site': 'same-site' });
+ expect(res.status).toBe(403);
+ expect(sessionsAsked).toBe(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('accepts what a service worker sends', async () => {
+ expect((await call(await markRead())).status).toBe(200);
+ expect(writes).toHaveLength(1);
+ });
+
+ it.each([
+ ['an unknown action', { action: 'delete' }],
+ ['an id that is no JMAP id', { emailId: '../../x' }],
+ ['no account', { accountId: undefined }],
+ ['no login', { login: undefined }],
+ ])('refuses %s', async (_name, over) => {
+ const res = await call(await markRead(over));
+ expect(res.status).toBe(400);
+ expect(sessionsAsked).toBe(0);
+ });
+});
+
+describe('which login', () => {
+ it('answers 401 with no cookie, without asking the mail server', async () => {
+ LOGINS = [];
+ expect((await call(await markRead())).status).toBe(401);
+ expect(sessionsAsked).toBe(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('answers 401 when the slot went to someone else since the notification', async () => {
+ // Account ids repeat, so bob's session would accept account `a` as well.
+ LOGINS = [BOB];
+ expect((await call(await markRead())).status).toBe(401);
+ expect(sessionsAsked).toBe(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('finds the login in whichever slot it holds now and uses its credential', async () => {
+ LOGINS = [BOB, null, ALICE];
+ expect((await call(await markRead())).status).toBe(200);
+ expect(writes[0].auth).toBe('Bearer alice');
+ });
+
+ it('answers 409 when the login is in two slots', async () => {
+ LOGINS = [ALICE, { ...ALICE, authHeader: 'Bearer stale' }];
+ expect((await call(await markRead())).status).toBe(409);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('matches a server address written differently on either side', async () => {
+ LOGINS = [{ ...ALICE, serverUrl: 'https://one.example' }];
+ const login = await loginFingerprint('https://ONE.example:443/', ALICE.username);
+ expect((await call(await markRead({ login }))).status).toBe(200);
+ expect(writes).toHaveLength(1);
+ });
+
+ it('answers 401 for an expired token: only a page refreshes it', async () => {
+ sessionStatus = 401;
+ expect((await call(await markRead())).status).toBe(401);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('answers 502 when the mail server is down, which says nothing about the token', async () => {
+ sessionStatus = 503;
+ expect((await call(await markRead())).status).toBe(502);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('refuses an account this login has no part in', async () => {
+ const res = await call(await markRead({ accountId: 'stranger' }));
+ expect(res.status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("doesn't take a name from Object.prototype for an account", async () => {
+ const res = await call(await markRead({ accountId: 'constructor' }));
+ expect(res.status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+});
+
+describe('session limits', () => {
+ // The page applies them, from activity and sign-in time: an action from here
+ // would keep the login going past them.
+ it.each([
+ ['a maximum session age', { maxHours: 8 }],
+ ['an idle limit', { idleMinutes: 30 }],
+ ])('answers 401 under %s, so the app opens and applies it', async (_name, session) => {
+ policy = { organisation: { session } };
+ expect((await call(await markRead())).status).toBe(401);
+ expect((await call(await archive())).status).toBe(401);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('follows the scope this login is in', async () => {
+ policy = { scopes: [{ id: 'team', label: 'Team', match: { domains: ['example.org'] }, policy: { organisation: { session: { maxHours: 8 } } } }] };
+ expect((await call(await markRead())).status).toBe(401);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("isn't troubled by a scope this login is not in", async () => {
+ policy = { scopes: [{ id: 'other', label: 'Other', match: { domains: ['other.test'] }, policy: { organisation: { session: { maxHours: 8 } } } }] };
+ expect((await call(await markRead())).status).toBe(200);
+ });
+
+ it("answers 401 when the login's scopes can't be worked out", async () => {
+ subject = null;
+ expect((await call(await markRead())).status).toBe(401);
+ expect(writes).toHaveLength(0);
+ });
+});
+
+describe('a message since moved to Trash or Junk', () => {
+ it.each(['trash', 'junk'])('stays as it is in %s, and the app opens it', async (role) => {
+ mailboxes = [INBOX, ARCHIVE, { id: 'bin', name: 'Bin', role }];
+ email = { id: 'e1', receivedAt: '2026-03-31T23:30:00Z', mailboxIds: { bin: true } };
+ expect((await call(await markRead())).status).toBe(409);
+ expect((await call(await archive())).status).toBe(409);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('answers 404 for Mark read on a message that is gone, writing nothing', async () => {
+ email = null;
+ expect((await call(await markRead())).status).toBe(404);
+ expect(writes).toHaveLength(0);
+ });
+});
+
+describe('Mark read', () => {
+ it('sets $seen on that message, at the rebased API address', async () => {
+ expect(await call(await markRead())).toEqual({ status: 200, body: { ok: true } });
+ expect(writes[0].url).toBe('https://one.example/jmap/');
+ expect(emailSet()).toEqual({ accountId: 'a', update: { e1: { 'keywords/$seen': true } } });
+ expect(mailboxSet()).toBeUndefined();
+ });
+
+ it('acts in a shared account the login reaches', async () => {
+ session.accounts = { ...(session.accounts as object), team: { name: 'team@example.org' } };
+ expect((await call(await markRead({ accountId: 'team' }))).status).toBe(200);
+ expect(emailSet().accountId).toBe('team');
+ });
+
+ it('answers 404 for a message that is gone', async () => {
+ emailSetResult = { notUpdated: { e1: { type: 'notFound' } } };
+ expect((await call(await markRead())).status).toBe(404);
+ });
+
+ it('answers 502 when the server refuses', async () => {
+ emailSetResult = { notUpdated: { e1: { type: 'forbidden' } } };
+ expect((await call(await markRead())).status).toBe(502);
+ });
+});
+
+describe('Archive', () => {
+ it('moves the message into the Archive folder', async () => {
+ expect((await call(await archive())).status).toBe(200);
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { arch: true } });
+ expect(mailboxSet()).toBeUndefined();
+ });
+
+ it('finds an Archive by name when no folder has the role, as the app does', async () => {
+ mailboxes = [INBOX, { id: 'named', name: 'archive' }];
+ await call(await archive());
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { named: true } });
+ });
+
+ it('creates the Archive folder when the account has none, in the same request', async () => {
+ mailboxes = [INBOX];
+ expect((await call(await archive())).status).toBe(200);
+ expect(mailboxSet()?.create).toEqual({ archive: { name: 'Archive', parentId: null, role: 'archive' } });
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { '#archive': true } });
+ });
+
+ it("doesn't try when the account may not create one", async () => {
+ mailboxes = [INBOX];
+ session.accounts = { a: { accountCapabilities: { 'urn:ietf:params:jmap:mail': { mayCreateTopLevelMailbox: false } } } };
+ expect((await call(await archive())).status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("doesn't try an Archive that takes no mail", async () => {
+ mailboxes = [INBOX, { ...ARCHIVE, myRights: { mayAddItems: false } }];
+ expect((await call(await archive())).status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('files by year into an existing year folder', async () => {
+ mailboxes = [INBOX, ARCHIVE, { id: 'y26', name: '2026', parentId: 'arch' }];
+ await call(await archive({ archiveMode: 'year', timeZone: 'UTC' }));
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { y26: true } });
+ expect(mailboxSet()).toBeUndefined();
+ });
+
+ it('ignores a folder named like the year elsewhere', async () => {
+ mailboxes = [INBOX, ARCHIVE, { id: 'other', name: '2026', parentId: 'inbox' }];
+ await call(await archive({ archiveMode: 'year', timeZone: 'UTC' }));
+ expect(mailboxSet()?.create).toEqual({ year: { name: '2026', parentId: 'arch' } });
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { '#year': true } });
+ });
+
+ it("files by month in the user's time zone, not the server's", async () => {
+ mailboxes = [INBOX, ARCHIVE, { id: 'y26', name: '2026', parentId: 'arch' }, { id: 'm03', name: '03', parentId: 'y26' }];
+ // 23:30 UTC on 31 March is 1 April in Berlin.
+ await call(await archive({ archiveMode: 'month', timeZone: 'Europe/Berlin' }));
+ expect(mailboxSet()?.create).toEqual({ month: { name: '04', parentId: 'y26' } });
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { '#month': true } });
+
+ writes.length = 0;
+ await call(await archive({ archiveMode: 'month', timeZone: 'UTC' }));
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { m03: true } });
+ });
+
+ it('creates the whole path in month mode on an account without an Archive', async () => {
+ mailboxes = [INBOX];
+ await call(await archive({ archiveMode: 'month', timeZone: 'UTC' }));
+ expect(mailboxSet()?.create).toEqual({
+ archive: { name: 'Archive', parentId: null, role: 'archive' },
+ year: { name: '2026', parentId: '#archive' },
+ month: { name: '03', parentId: '#year' },
+ });
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { '#month': true } });
+ });
+
+ it('survives a time zone that is no time zone', async () => {
+ mailboxes = [INBOX, ARCHIVE, { id: 'y26', name: '2026', parentId: 'arch' }];
+ expect((await call(await archive({ archiveMode: 'year', timeZone: 'Mars/Olympus' }))).status).toBe(200);
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { y26: true } });
+ });
+
+ it('answers 404 for a message that is gone', async () => {
+ email = null;
+ expect((await call(await archive())).status).toBe(404);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('files into a folder another client made first, on one more try', async () => {
+ mailboxes = [INBOX, ARCHIVE];
+ mailboxesOnSecondRead = [INBOX, ARCHIVE, { id: 'y26', name: '2026', parentId: 'arch' }];
+ mailboxSetResults = [{ notCreated: { year: { type: 'alreadyExists' } } }];
+ emailSetResults = [{ notUpdated: { e1: { type: 'invalidProperties' } } }];
+ expect((await call(await archive({ archiveMode: 'year', timeZone: 'UTC' }))).status).toBe(200);
+ expect(mailboxReads).toBe(2);
+ expect(writes).toHaveLength(2);
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { y26: true } });
+ expect(destroyed()).toBeUndefined();
+ });
+
+ it('tries only once more, and stops when the second try fails too', async () => {
+ mailboxes = [INBOX, ARCHIVE];
+ mailboxSetResults = [
+ { notCreated: { year: { type: 'alreadyExists' } } },
+ { notCreated: { year: { type: 'alreadyExists' } } },
+ ];
+ emailSetResult = { notUpdated: { e1: { type: 'invalidProperties' } } };
+ expect((await call(await archive({ archiveMode: 'year', timeZone: 'UTC' }))).status).toBe(502);
+ expect(writes).toHaveLength(2);
+ });
+
+ it('leaves no empty folder when the message then is refused, deepest first', async () => {
+ mailboxes = [INBOX];
+ emailSetResult = { notUpdated: { e1: { type: 'forbidden' } } };
+ expect((await call(await archive({ archiveMode: 'month', timeZone: 'UTC' }))).status).toBe(502);
+ expect(destroyed()).toEqual(['new-month', 'new-year', 'new-archive']);
+ });
+
+ it('keeps the folders it made when the message went in', async () => {
+ mailboxes = [INBOX];
+ expect((await call(await archive({ archiveMode: 'month', timeZone: 'UTC' }))).status).toBe(200);
+ expect(destroyed()).toBeUndefined();
+ });
+
+ it("files into an Archive shared with others, as the app's own button does", async () => {
+ mailboxes = [INBOX, { ...ARCHIVE, shareWith: { u2: { mayReadItems: true } } }];
+ expect((await call(await archive())).status).toBe(200);
+ expect(emailSet().update.e1).toEqual({ mailboxIds: { arch: true } });
+ });
+
+ describe('the admin gate', () => {
+ it('refuses when the admin turned Archive off, whatever the worker believes', async () => {
+ policy = { features: { archiveActionEnabled: false } };
+ expect((await call(await archive())).status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('follows the scope this login is in', async () => {
+ policy = { scopes: [{ id: 'team', label: 'Team', match: { domains: ['example.org'] }, policy: { features: { archiveActionEnabled: false } } }] };
+ expect((await call(await archive())).status).toBe(403);
+ expect(writes).toHaveLength(0);
+ });
+
+
+ it("refuses when the login's scopes can't be worked out", async () => {
+ subject = null;
+ expect((await call(await archive())).status).toBe(401);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('leaves Mark read alone', async () => {
+ policy = { features: { archiveActionEnabled: false } };
+ expect((await call(await markRead())).status).toBe(200);
+ });
+ });
+});
diff --git a/lib/__tests__/push-preview-route.test.ts b/lib/__tests__/push-preview-route.test.ts
index 3880595cb..a7abae5ca 100644
--- a/lib/__tests__/push-preview-route.test.ts
+++ b/lib/__tests__/push-preview-route.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { endlessResponse } from './helpers/endless-body';
+import { loginFingerprint } from '@/lib/pwa-notify/login-fingerprint';
vi.mock('next/server', () => ({
NextResponse: {
@@ -112,6 +113,11 @@ describe('push preview route account resolution', () => {
expect(mailboxQuery?.methodCalls[0][1].accountId).toBe('g');
});
+ it('names the login for a message, as the action route knows it', async () => {
+ const { body } = await callRoute('a');
+ expect(body.login).toBe(await loginFingerprint('https://mail.example.com', undefined));
+ });
+
it('names the login (cookie slot) the account belongs to', async () => {
// The worker only knows the JMAP account id, which can repeat across
// servers; the click must open the message in this login.
@@ -186,7 +192,7 @@ describe('push preview JMAP failures', () => {
['Email/get', { list: [{ id: 'd', threadId: 'td' }] }, 'delivered'],
] }));
expect(await callRoute('a', 'd')).toEqual({
- status: 200, body: { email: { id: 'd', threadId: 'td' }, unreadTotal: 1, slot: 0 },
+ status: 200, body: { email: { id: 'd', threadId: 'td' }, unreadTotal: 1, slot: 0, login: expect.any(String) },
});
});
});
@@ -202,7 +208,7 @@ it('previews a delivered message outside an empty Inbox', async () => {
['Email/get', { list: [{ id: 'filed', threadId: 't2' }] }, 'delivered'],
] }));
expect(await callRoute('a', 'filed')).toEqual({
- status: 200, body: { email: { id: 'filed', threadId: 't2' }, unreadTotal: 1, slot: 0 },
+ status: 200, body: { email: { id: 'filed', threadId: 't2' }, unreadTotal: 1, slot: 0, login: expect.any(String) },
});
});
diff --git a/lib/__tests__/sign-out-cleanup.test.ts b/lib/__tests__/sign-out-cleanup.test.ts
index 270fc1606..355f623e6 100644
--- a/lib/__tests__/sign-out-cleanup.test.ts
+++ b/lib/__tests__/sign-out-cleanup.test.ts
@@ -6,6 +6,7 @@ vi.mock('@/lib/plugin-storage', () => ({
import { fileStorage } from '@/lib/plugin-storage';
import { broadcastSignOut, onSignedOutElsewhere, purgeSignedOutData } from '@/lib/sign-out-cleanup';
+import { handOffFiles, pendingHandoffs } from '@/lib/launch-handoff';
// A full sign-out left search history, open tabs (with subjects), Files
// favourites and staged attachment bytes behind for the next person at the
@@ -14,6 +15,13 @@ import { broadcastSignOut, onSignedOutElsewhere, purgeSignedOutData } from '@/li
beforeEach(() => localStorage.clear());
describe('purgeSignedOutData', () => {
+ it('forgets files and links on their way into an account', () => {
+ handOffFiles([new File(['x'], 'a.ics')], 'calendar');
+ expect(pendingHandoffs()).toHaveLength(1);
+ purgeSignedOutData();
+ expect(pendingHandoffs()).toHaveLength(0);
+ });
+
it("removes the accounts' leftovers and keeps device preferences", () => {
for (const key of [
'email-snapshot', 'pro-tabs', 'search-history-storage', 'calendar-storage',
diff --git a/lib/__tests__/sw-harness.ts b/lib/__tests__/sw-harness.ts
index d54631a62..c9a20f1ea 100644
--- a/lib/__tests__/sw-harness.ts
+++ b/lib/__tests__/sw-harness.ts
@@ -29,17 +29,41 @@ export class FakeCaches {
}
}
-export function loadWorker(opts: { buildId: string; caches: FakeCaches; clients: Array<{ id: string }>; fetch?: (input: unknown) => Promise }) {
+export interface ShownNotification {
+ title: string;
+ options: Record;
+}
+
+export function loadWorker(opts: {
+ buildId: string;
+ caches: FakeCaches;
+ clients: Array<{ id: string }>;
+ fetch?: (input: unknown, init?: RequestInit) => Promise;
+ /** More globals of a real worker: Notification, NotificationEvent, MessageChannel. */
+ globals?: Record;
+ openWindow?: (url: string) => Promise;
+ /** What showNotification does, after it was recorded in `shown`. */
+ showNotification?: (title: string, options: Record) => Promise;
+ notifications?: Array>;
+ location?: string;
+}) {
const listeners = new Map void>();
+ const shown: ShownNotification[] = [];
let skipped = 0;
const self = {
- location: { href: `https://mail.example.com/sw.js?v=${opts.buildId}`, origin: 'https://mail.example.com' },
+ location: { href: opts.location ?? `https://mail.example.com/sw.js?v=${opts.buildId}`, origin: 'https://mail.example.com' },
addEventListener: (type: string, fn: (event: unknown) => void) => listeners.set(type, fn),
skipWaiting: () => { skipped++; },
- clients: { claim: async () => {}, matchAll: async () => opts.clients },
- registration: { showNotification: async () => {}, getNotifications: async () => [] },
+ clients: { claim: async () => {}, matchAll: async () => opts.clients, openWindow: opts.openWindow },
+ registration: {
+ showNotification: async (title: string, options: Record) => {
+ shown.push({ title, options });
+ await opts.showNotification?.(title, options);
+ },
+ getNotifications: async () => opts.notifications ?? [],
+ },
};
- const context = vm.createContext({ self, caches: opts.caches, fetch: opts.fetch ?? (async () => { throw new TypeError('offline'); }), URL, URLSearchParams, Request, Response, Headers, Date, console, AbortController, setTimeout, clearTimeout });
+ const context = vm.createContext({ self, caches: opts.caches, fetch: opts.fetch ?? (async () => { throw new TypeError('offline'); }), URL, URLSearchParams, Request, Response, Headers, Date, console, AbortController, setTimeout, clearTimeout, crypto: globalThis.crypto, TextEncoder, btoa, ...opts.globals });
vm.runInContext(SW_SOURCE, context);
async function dispatch(type: string, event: Record = {}) {
const waits: Promise[] = [];
@@ -52,5 +76,5 @@ export function loadWorker(opts: { buildId: string; caches: FakeCaches; clients:
listeners.get('fetch')?.({ request: { method: 'GET', mode: 'cors', ...req }, respondWith: (p: Promise) => { answer = p; } });
return answer ? await answer : null;
}
- return { dispatch, listeners, request, skipped: () => skipped };
+ return { dispatch, listeners, request, shown, skipped: () => skipped };
}
diff --git a/lib/__tests__/sw-notification-actions.test.ts b/lib/__tests__/sw-notification-actions.test.ts
new file mode 100644
index 000000000..96e94949f
--- /dev/null
+++ b/lib/__tests__/sw-notification-actions.test.ts
@@ -0,0 +1,446 @@
+import { describe, expect, it, vi } from 'vitest';
+import { FakeCaches, loadWorker } from './sw-harness';
+
+// A notification's Archive, Mark read and Reply buttons (public/sw.js). The
+// worker has no login: an open tab goes first, then the cookie route, then the
+// message opens in the app.
+
+const ORIGIN = 'https://mail.example.com';
+const PUSH_CACHE = 'bulwark-push-state-v1';
+const PREFS = {
+ archiveEnabled: true,
+ archiveMode: 'month',
+ pluginsMayVeto: false,
+ labels: { archive: 'Archivieren', markRead: 'Als gelesen markieren', reply: 'Antworten', replyPlaceholder: 'Antwort schreiben' },
+};
+const ONE_MESSAGE = { kind: 'email', emailId: 'e1', threadId: 't1', accountId: 'a', slot: 2, login: 'fp' };
+const MESSAGE_URL = '/mail/message/e1?slot=2&owner=a';
+
+async function cachesWith(prefs?: unknown) {
+ const caches = new FakeCaches();
+ if (prefs) {
+ const cache = await caches.open(PUSH_CACHE);
+ await cache.put(`${ORIGIN}/__push-state/actions`, new Response(JSON.stringify(prefs)));
+ }
+ return caches;
+}
+
+/** A window client that answers a posted action with the given statuses. */
+function tab(id: string, statuses: string[], extra: Record = {}) {
+ const messages: Array> = [];
+ const client = {
+ id,
+ url: `${ORIGIN}/mail/folder/inbox`,
+ messages,
+ focus: vi.fn(async function focus(this: unknown) { return client; }),
+ navigate: vi.fn(async () => client),
+ postMessage(message: Record, ports?: MessagePort[]) {
+ messages.push(message);
+ if (message.kind !== 'notification-action') return;
+ const port = ports?.[0];
+ for (const status of statuses) port?.postMessage({ status });
+ },
+ ...extra,
+ };
+ return client;
+}
+
+function worker(opts: {
+ caches: FakeCaches;
+ clients?: Array<{ id: string }>;
+ fetch?: (input: unknown, init?: RequestInit) => Promise;
+ max?: number | null;
+ inline?: boolean;
+ showNotification?: (title: string, options: Record) => Promise;
+ notifications?: Array>;
+}) {
+ const openWindow = vi.fn(async () => null);
+ const fetch = vi.fn(opts.fetch ?? (async () => new Response('{}', { status: 200 })));
+ const max = opts.max === undefined ? 3 : opts.max;
+ const loaded = loadWorker({
+ buildId: 'b1',
+ caches: opts.caches,
+ clients: opts.clients ?? [],
+ fetch,
+ openWindow,
+ showNotification: opts.showNotification,
+ notifications: opts.notifications,
+ globals: {
+ MessageChannel,
+ ...(max === null ? {} : { Notification: { maxActions: max } }),
+ ...(opts.inline ? { NotificationEvent: class { get reply() { return null; } } } : {}),
+ },
+ });
+ const click = (action: string, extra: Record = {}, data: Record = ONE_MESSAGE) =>
+ loaded.dispatch('notificationclick', { action, ...extra, notification: { data, tag: 'bulwark-mail:a', close() {} } });
+ const posts = () => fetch.mock.calls.filter(([, init]) => init?.method === 'POST');
+ return { ...loaded, click, openWindow, fetch, posts };
+}
+
+const pushFor = (preview: Record) => async (w: ReturnType) => {
+ await w.dispatch('push', { data: { json: () => ({ kind: 'jmap-email-push', accountId: 'a', emailIds: ['e1'] }) } });
+ return preview;
+};
+
+const previewOf = (unreadTotal: number) => JSON.stringify({
+ unreadTotal,
+ slot: 2,
+ login: 'fp',
+ email: { id: 'e1', threadId: 't1', subject: 'Hello', from: [{ name: 'Bob' }] },
+});
+
+describe('the buttons a notification gets', () => {
+ const buttonsFor = async (opts: { prefs?: unknown; max?: number | null; inline?: boolean; unreadTotal?: number }) => {
+ const w = worker({
+ caches: await cachesWith(opts.prefs),
+ max: opts.max,
+ inline: opts.inline,
+ fetch: async () => new Response(previewOf(opts.unreadTotal ?? 1), { status: 200 }),
+ });
+ await pushFor({})(w);
+ expect(w.shown).toHaveLength(1);
+ return w.shown[0].options.actions as Array> | undefined;
+ };
+
+ it('offers the three in the labels the page left, on one message', async () => {
+ expect(await buttonsFor({ prefs: PREFS })).toEqual([
+ { action: 'archive', title: 'Archivieren' },
+ { action: 'mark-read', title: 'Als gelesen markieren' },
+ { action: 'reply', title: 'Antworten' },
+ ]);
+ });
+
+ it('keeps Archive and Reply where the browser has two buttons', async () => {
+ const buttons = await buttonsFor({ prefs: PREFS, max: 2 });
+ expect(buttons?.map((b) => b.action)).toEqual(['archive', 'reply']);
+ });
+
+ it('leaves Archive out when the admin turned it off', async () => {
+ const buttons = await buttonsFor({ prefs: { ...PREFS, archiveEnabled: false }, max: 2 });
+ expect(buttons?.map((b) => b.action)).toEqual(['mark-read', 'reply']);
+ });
+
+ it('offers no Archive, in English, before any page has spoken', async () => {
+ expect(await buttonsFor({})).toEqual([
+ { action: 'mark-read', title: 'Mark as read' },
+ { action: 'reply', title: 'Reply' },
+ ]);
+ });
+
+ it('adds nothing in a browser without notification buttons', async () => {
+ expect(await buttonsFor({ prefs: PREFS, max: null })).toBeUndefined();
+ expect(await buttonsFor({ prefs: PREFS, max: 0 })).toBeUndefined();
+ });
+
+ it('gives the group notification none: it names no message', async () => {
+ expect(await buttonsFor({ prefs: PREFS, unreadTotal: 4 })).toBeUndefined();
+ });
+
+ it('gives a message without its login none', async () => {
+ const w = worker({
+ caches: await cachesWith(PREFS),
+ fetch: async () => new Response(JSON.stringify({ unreadTotal: 1, slot: 2, email: { id: 'e1', threadId: 't1' } }), { status: 200 }),
+ });
+ await pushFor({})(w);
+ expect(w.shown[0].options.actions).toBeUndefined();
+ });
+
+ it('makes Reply a text field only where the browser can hand the text back', async () => {
+ const buttons = await buttonsFor({ prefs: PREFS, inline: true });
+ expect(buttons?.find((b) => b.action === 'reply')).toEqual({
+ action: 'reply', title: 'Antworten', type: 'text', placeholder: 'Antwort schreiben',
+ });
+ });
+
+ it('still shows the notification when the browser refuses the buttons', async () => {
+ const w = worker({
+ caches: await cachesWith(PREFS),
+ fetch: async () => new Response(previewOf(1), { status: 200 }),
+ showNotification: async (_title, options) => {
+ if (options.actions) throw new TypeError('bad action');
+ },
+ });
+ await pushFor({})(w);
+ expect(w.shown).toHaveLength(2);
+ expect(w.shown[1].options.actions).toBeUndefined();
+ expect(w.shown[1].options.data).toMatchObject({ emailId: 'e1', login: 'fp' });
+ });
+
+ it('keeps the buttons when a redelivered push shows the same notification again', async () => {
+ const existing = { title: 'Bob', body: 'Hello', data: ONE_MESSAGE };
+ const caches = await cachesWith(PREFS);
+ const cache = await caches.open(PUSH_CACHE);
+ await cache.put(`${ORIGIN}/__push-state/notified/a`, new Response(JSON.stringify({ ids: ['e1'] })));
+ const w = worker({ caches, notifications: [existing] });
+ await pushFor({})(w);
+ expect(w.shown).toHaveLength(1);
+ expect((w.shown[0].options.actions as unknown[]).length).toBe(3);
+ });
+});
+
+describe('a click', () => {
+ it('on the body works as before: it opens the message and runs nothing', async () => {
+ const client = tab('t', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('');
+ expect(client.navigate).toHaveBeenCalledWith(MESSAGE_URL);
+ expect(client.messages.map((m) => m.kind)).toEqual(['notificationclick']);
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('on an unknown button counts as a click on the body', async () => {
+ const client = tab('t', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('explode');
+ expect(client.navigate).toHaveBeenCalledWith(MESSAGE_URL);
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('on a button of a group notification opens the inbox and runs nothing', async () => {
+ const client = tab('t', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('archive', {}, { kind: 'mail-list', accountId: 'a', slot: 2 });
+ expect(client.navigate).toHaveBeenCalledWith('/mail/folder/inbox?slot=2&owner=a');
+ expect(w.posts()).toHaveLength(0);
+ });
+});
+
+describe('Mark read and Archive', () => {
+ it('go to an open tab first, which leaves nothing else to do', async () => {
+ const client = tab('t', ['accepted', 'done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('mark-read');
+ expect(client.messages.find((m) => m.kind === 'notification-action')).toEqual({
+ kind: 'notification-action', action: 'mark-read', emailId: 'e1', threadId: 't1', accountId: 'a', slot: 2, login: 'fp', at: expect.any(Number),
+ });
+ expect(w.posts()).toHaveLength(0);
+ expect(client.navigate).not.toHaveBeenCalled();
+ expect(client.focus).not.toHaveBeenCalled();
+ expect(w.openWindow).not.toHaveBeenCalled();
+ });
+
+ it('go to the tab in front first', async () => {
+ const hidden = tab('hidden', ['done'], { visibilityState: 'hidden' });
+ const front = tab('front', ['done'], { focused: true, visibilityState: 'visible' });
+ const w = worker({ caches: await cachesWith(PREFS), clients: [hidden, front] });
+ await w.click('mark-read');
+ expect(front.messages.some((m) => m.kind === 'notification-action')).toBe(true);
+ expect(hidden.messages.some((m) => m.kind === 'notification-action')).toBe(false);
+ });
+
+ it('try the next tab when one declines', async () => {
+ const other = tab('other', ['declined']);
+ const right = tab('right', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [other, right] });
+ await w.click('mark-read');
+ expect(right.messages.some((m) => m.kind === 'notification-action')).toBe(true);
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('use the route with no tab open, and nothing opens when it works', async () => {
+ const w = worker({ caches: await cachesWith(PREFS) });
+ await w.click('mark-read');
+ expect(w.posts()).toHaveLength(1);
+ const [url, init] = w.posts()[0];
+ expect(url).toBe('/api/push/action');
+ expect(init?.credentials).toBe('include');
+ expect(JSON.parse(String(init?.body))).toEqual({ action: 'mark-read', accountId: 'a', emailId: 'e1', login: 'fp' });
+ expect(w.openWindow).not.toHaveBeenCalled();
+ });
+
+ it('send the mirrored archive mode and the time zone with Archive', async () => {
+ const w = worker({ caches: await cachesWith(PREFS) });
+ await w.click('archive');
+ const body = JSON.parse(String(w.posts()[0][1]?.body));
+ expect(body).toMatchObject({ action: 'archive', archiveMode: 'month', accountId: 'a', emailId: 'e1', login: 'fp' });
+ expect(typeof body.timeZone).toBe('string');
+ expect(body.timeZone).not.toBe('');
+ });
+
+ it('send when they asked, so a tab that thaws later can tell', async () => {
+ const client = tab('t', ['done']);
+ const before = Date.now();
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('mark-read');
+ const at = client.messages.find((m) => m.kind === 'notification-action')?.at as number;
+ expect(at).toBeGreaterThanOrEqual(before);
+ expect(at).toBeLessThanOrEqual(Date.now());
+ });
+
+ it('leave the route alone while an enabled plugin may stop them, and open the message', async () => {
+ const w = worker({ caches: await cachesWith({ ...PREFS, pluginsMayVeto: true }) });
+ await w.click('mark-read');
+ expect(w.posts()).toHaveLength(0);
+ expect(w.openWindow).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('leave the route alone before any page has said what plugins there are', async () => {
+ const w = worker({ caches: await cachesWith() });
+ await w.click('mark-read');
+ expect(w.posts()).toHaveLength(0);
+ expect(w.openWindow).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('open the message when a tab holding this login stays silent, without the route', async () => {
+ const silent = tab('held', []);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [silent] });
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['fp'] }, source: { id: 'held' } });
+ await w.click('archive');
+ expect(w.posts()).toHaveLength(0);
+ expect(silent.focus).toHaveBeenCalled();
+ expect(silent.navigate).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('give a busy tab holding this login longer than the others', async () => {
+ const busy = tab('held', []);
+ const post = busy.postMessage;
+ busy.postMessage = (message: Record, ports?: MessagePort[]) => {
+ post(message, ports);
+ if (message.kind === 'notification-action') setTimeout(() => ports?.[0]?.postMessage({ status: 'done' }), 1_500);
+ };
+ const w = worker({ caches: await cachesWith(PREFS), clients: [busy] });
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['fp'] }, source: { id: 'held' } });
+ await w.click('mark-read');
+ expect(busy.navigate).not.toHaveBeenCalled();
+ expect(w.posts()).toHaveLength(0);
+ expect(w.openWindow).not.toHaveBeenCalled();
+ });
+
+ it('take another tab that answers over a silent one holding this login', async () => {
+ const silent = tab('held', [], { visibilityState: 'visible', focused: true });
+ const alive = tab('alive', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [silent, alive] });
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['fp'] }, source: { id: 'held' } });
+ await w.click('mark-read');
+ expect(alive.messages.some((m) => m.kind === 'notification-action')).toBe(true);
+ expect(silent.navigate).not.toHaveBeenCalled();
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('forget tabs that are gone when another reports its logins', async () => {
+ const caches = await cachesWith(PREFS);
+ const clients = [tab('one', []), tab('two', [])];
+ const w = worker({ caches, clients });
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['fp'] }, source: { id: 'one' } });
+ clients.shift();
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['other'] }, source: { id: 'two' } });
+ const cache = await caches.open(PUSH_CACHE);
+ expect(await (await cache.match(`${ORIGIN}/__push-state/client-logins`))!.json()).toEqual({ two: ['other'] });
+ });
+
+ it('use the route when a tab never answers, so a frozen tab costs a moment only', async () => {
+ const frozen = tab('frozen', []);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [frozen] });
+ await w.click('mark-read');
+ expect(w.posts()).toHaveLength(1);
+ expect(frozen.navigate).not.toHaveBeenCalled();
+ });
+
+ it.each([401, 403, 404, 409, 502])('open the message when the route answers %i', async (status) => {
+ const w = worker({ caches: await cachesWith(PREFS), fetch: async () => new Response('{}', { status }) });
+ await w.click('archive');
+ expect(w.posts()).toHaveLength(1);
+ expect(w.openWindow).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('open the message when the route is out of reach', async () => {
+ const w = worker({ caches: await cachesWith(PREFS), fetch: async () => { throw new TypeError('offline'); } });
+ await w.click('mark-read');
+ expect(w.openWindow).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('open the message when a tab with a live login tried and failed, without the route', async () => {
+ const client = tab('t', ['accepted', 'failed']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('archive');
+ expect(w.posts()).toHaveLength(0);
+ expect(client.focus).toHaveBeenCalled();
+ expect(client.navigate).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+
+ it('never post an Archive the mirror says is off', async () => {
+ const w = worker({ caches: await cachesWith({ ...PREFS, archiveEnabled: false }) });
+ await w.click('archive');
+ expect(w.posts()).toHaveLength(0);
+ expect(w.openWindow).toHaveBeenCalledWith(MESSAGE_URL);
+ });
+});
+
+describe('Reply', () => {
+ it('opens the composer in an open tab and brings it to the front', async () => {
+ const client = tab('t', ['done']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('reply', { reply: ' Thanks! ' });
+ expect(client.messages.find((m) => m.kind === 'notification-action')).toMatchObject({ action: 'reply', emailId: 'e1', text: 'Thanks!' });
+ expect(client.focus).toHaveBeenCalled();
+ expect(client.navigate).not.toHaveBeenCalled();
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('navigates a tab that has no mail page to the reply link', async () => {
+ const client = tab('t', ['declined']);
+ const w = worker({ caches: await cachesWith(PREFS), clients: [client] });
+ await w.click('reply');
+ expect(client.focus).toHaveBeenCalled();
+ expect(client.navigate).toHaveBeenCalledWith(`${MESSAGE_URL}&reply=1`);
+ });
+
+ it('opens a window on the reply link with no tab open, never through the route', async () => {
+ const w = worker({ caches: await cachesWith(PREFS) });
+ await w.click('reply');
+ expect(w.openWindow).toHaveBeenCalledWith(`${MESSAGE_URL}&reply=1`);
+ expect(w.posts()).toHaveLength(0);
+ });
+
+ it('keeps typed text in the store for the page, out of the URL', async () => {
+ const caches = await cachesWith(PREFS);
+ const w = worker({ caches });
+ await w.click('reply', { reply: 'Private words' });
+ expect(w.openWindow).toHaveBeenCalledWith(`${MESSAGE_URL}&reply=1`);
+ const cache = await caches.open(PUSH_CACHE);
+ const kept = await (await cache.match(`${ORIGIN}/__push-state/pending-reply`))!.json();
+ expect(kept).toMatchObject({ emailId: 'e1', text: 'Private words' });
+ });
+
+ it('keeps typed text and the reply link when a tab holding this login stays silent', async () => {
+ const caches = await cachesWith(PREFS);
+ const silent = tab('held', []);
+ const w = worker({ caches, clients: [silent] });
+ await w.dispatch('message', { data: { type: 'client-logins', logins: ['fp'] }, source: { id: 'held' } });
+ await w.click('reply', { reply: 'Private words' });
+ expect(silent.navigate).toHaveBeenCalledWith(`${MESSAGE_URL}&reply=1`);
+ const cache = await caches.open(PUSH_CACHE);
+ expect(await (await cache.match(`${ORIGIN}/__push-state/pending-reply`))!.json()).toMatchObject({ text: 'Private words' });
+ });
+
+ it('leaves nothing in the store without typed text', async () => {
+ const caches = await cachesWith(PREFS);
+ const w = worker({ caches });
+ await w.click('reply', { reply: ' ' });
+ const cache = await caches.open(PUSH_CACHE);
+ expect(await cache.match(`${ORIGIN}/__push-state/pending-reply`)).toBeUndefined();
+ });
+});
+
+describe('Background Sync', () => {
+ it('tells every open tab to flush the outbox', async () => {
+ const one = tab('one', []);
+ const two = tab('two', []);
+ const w = worker({ caches: await cachesWith(), clients: [one, two] });
+ await w.dispatch('sync', { tag: 'bulwark-outbox' });
+ expect(one.messages).toEqual([{ kind: 'outbox-flush' }]);
+ expect(two.messages).toEqual([{ kind: 'outbox-flush' }]);
+ });
+
+ it('ignores other tags', async () => {
+ const one = tab('one', []);
+ const w = worker({ caches: await cachesWith(), clients: [one] });
+ await w.dispatch('sync', { tag: 'something-else' });
+ expect(one.messages).toEqual([]);
+ });
+
+ it('settles with no tab open', async () => {
+ const w = worker({ caches: await cachesWith(), clients: [] });
+ await expect(w.dispatch('sync', { tag: 'bulwark-outbox' })).resolves.toBeUndefined();
+ });
+});
diff --git a/lib/__tests__/sw-share-target.test.ts b/lib/__tests__/sw-share-target.test.ts
new file mode 100644
index 000000000..57509a55f
--- /dev/null
+++ b/lib/__tests__/sw-share-target.test.ts
@@ -0,0 +1,283 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+import { FakeCaches, loadWorker } from './sw-harness';
+
+// The manifest's share_target POST, in the service worker, and a mailto:
+// launch while offline. Any site can POST here, signed in or not, so what the
+// worker keeps is limited and sealed. Before: a POST went to the server when
+// offline mode was off, and files sat readable in the cache with no limit.
+
+const ORIGIN = 'https://mail.example.com';
+const CACHE = 'bulwark-launch-handoff-v1';
+const TTL = 15 * 60 * 1000;
+const settle = () => new Promise((r) => setTimeout(r, 0));
+
+function shareRequest(form: FormData, overrides: Record = {}) {
+ return { url: `${ORIGIN}/protocol/share`, method: 'POST', mode: 'navigate', destination: 'document', formData: async () => form, ...overrides } as never;
+}
+
+function sharedForm(): FormData {
+ const form = new FormData();
+ form.set('title', 'A link');
+ form.set('text', 'Look');
+ form.set('url', 'https://example.org/');
+ form.append('files', new File(['secret bytes'], 'photo.png', { type: 'image/png' }));
+ return form;
+}
+
+const landingOf = (answer: Response | null) => {
+ const url = new URL(answer!.headers.get('location')!);
+ return { url, fragment: new URLSearchParams(url.hash.slice(1)) };
+};
+
+async function shellOn(caches: FakeCaches, on: boolean) {
+ const cache = await caches.open('bulwark-sw-state-v1');
+ await cache.put('/__bulwark/offline-shell', new Response(JSON.stringify({ on })));
+}
+
+async function plantEntry(caches: FakeCaches, id: string, createdAt: number, bytes = 0) {
+ const store = await caches.open(CACHE);
+ await store.put(`/__bulwark/handoff/${id}/meta`, new Response(JSON.stringify({ kind: 'compose', createdAt, bytes })));
+ await store.put(`/__bulwark/handoff/${id}/sealed`, new Response('x'));
+}
+
+async function entryIds(caches: FakeCaches): Promise {
+ const store = await caches.open(CACHE);
+ return (await store.keys()).filter((key) => key.url.endsWith('/meta')).map((key) => key.url.split('/').slice(-2)[0]);
+}
+
+function htmlPage(body: string) {
+ const res = new Response(body, { status: 200, headers: { 'Content-Type': 'text/html' } });
+ Object.defineProperty(res, 'type', { value: 'basic' });
+ return res;
+}
+
+describe('share target', () => {
+ it.each([[false], [true]])('takes the POST with offline mode on=%s, keeps the files sealed and goes to the app', async (on) => {
+ const caches = new FakeCaches();
+ await shellOn(caches, on);
+ const fetchMock = vi.fn();
+ const worker = loadWorker({ buildId: 'a', caches, clients: [], fetch: fetchMock });
+ await settle();
+
+ const answer = await worker.request(shareRequest(sharedForm()));
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(answer?.status).toBe(303);
+ const { url, fragment } = landingOf(answer);
+ expect(`${url.origin}${url.pathname}`).toBe(`${ORIGIN}/`);
+ // Id and key in the fragment: neither ever reaches the server.
+ expect(url.search).toBe('');
+ const id = fragment.get('share')!;
+ expect(id).toMatch(/^[\w-]+$/);
+ expect(fragment.get('key')).toMatch(/^[\w-]{43}$/);
+
+ const store = await caches.open(CACHE);
+ const meta = (await (await store.match(`/__bulwark/handoff/${id}/meta`))!.json()) as Record;
+ expect(meta).toMatchObject({ kind: 'compose', bytes: 12 });
+ // Only what a sweep needs is readable.
+ expect(Object.keys(meta).sort()).toEqual(['bytes', 'createdAt', 'kind']);
+ for (const part of ['meta', 'sealed', '0']) {
+ const text = await (await store.match(`/__bulwark/handoff/${id}/${part}`))!.text();
+ for (const secret of ['secret bytes', 'photo.png', 'A link', 'example.org']) expect(text).not.toContain(secret);
+ }
+ });
+
+ it('answers while the worker has only just started and has not read its state', async () => {
+ const worker = loadWorker({ buildId: 'a', caches: new FakeCaches(), clients: [] });
+ const answer = await worker.request(shareRequest(sharedForm()));
+ expect(answer?.status).toBe(303);
+ });
+
+ it('works under a subpath', async () => {
+ const worker = loadWorker({ buildId: 'a', caches: new FakeCaches(), clients: [], location: `${ORIGIN}/webmail/sw.js?v=a` });
+ expect(await worker.request(shareRequest(sharedForm()))).toBeNull();
+ const answer = await worker.request(shareRequest(sharedForm(), { url: `${ORIGIN}/webmail/protocol/share` }));
+ expect(answer!.headers.get('location')).toContain(`${ORIGIN}/webmail/#share=`);
+ });
+
+ it('skips empty file fields', async () => {
+ const caches = new FakeCaches();
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const form = new FormData();
+ form.set('url', 'https://example.org/');
+ form.append('files', new File([], ''));
+ const answer = await worker.request(shareRequest(form));
+ const id = landingOf(answer).fragment.get('share')!;
+ const store = await caches.open(CACHE);
+ const meta = (await (await store.match(`/__bulwark/handoff/${id}/meta`))!.json()) as { bytes: number };
+ expect(meta.bytes).toBe(0);
+ expect(await store.match(`/__bulwark/handoff/${id}/0`)).toBeUndefined();
+ });
+
+ it('keeps the text and says the files are lost when there is no room', async () => {
+ const caches = new FakeCaches();
+ const original = caches.open.bind(caches);
+ const store = await original(CACHE);
+ vi.spyOn(caches, 'open').mockImplementation(async (name: string) => (name === CACHE
+ ? { ...store, put: async () => { throw new Error('QuotaExceededError'); } }
+ : original(name)));
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+
+ const { fragment } = landingOf(await worker.request(shareRequest(sharedForm())));
+
+ expect(fragment.get('share')).toBe('unavailable');
+ expect(fragment.get('share_files')).toBe('1');
+ expect(fragment.get('share_title')).toBe('A link');
+ expect(fragment.get('share_url')).toBe('https://example.org/');
+ expect((await store.keys()).length).toBe(0);
+ });
+
+ it('keeps that address short too, and says it cut', async () => {
+ const caches = new FakeCaches();
+ const original = caches.open.bind(caches);
+ const store = await original(CACHE);
+ vi.spyOn(caches, 'open').mockImplementation(async (name: string) => (name === CACHE
+ ? { ...store, put: async () => { throw new Error('QuotaExceededError'); } }
+ : original(name)));
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const form = new FormData();
+ form.set('text', 'あ'.repeat(3000));
+
+ const answer = await worker.request(shareRequest(form));
+
+ expect(answer!.headers.get('location')!.length).toBeLessThan(4000);
+ expect(landingOf(answer).fragment.get('share_cut')).toBe('1');
+ });
+
+ it('says so when the form cannot be read', async () => {
+ const worker = loadWorker({ buildId: 'a', caches: new FakeCaches(), clients: [] });
+ const answer = await worker.request(shareRequest(new FormData(), { formData: async () => { throw new TypeError('bad body'); } }));
+ const { fragment } = landingOf(answer);
+ expect(fragment.get('share')).toBe('unavailable');
+ expect(fragment.get('share_files')).toBe('1');
+ });
+
+ it('leaves other requests alone', async () => {
+ const caches = new FakeCaches();
+ await shellOn(caches, false);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await settle();
+ // A fetch from a page, a POST elsewhere, another origin, and a plain GET.
+ expect(await worker.request(shareRequest(sharedForm(), { mode: 'cors' }))).toBeNull();
+ expect(await worker.request(shareRequest(sharedForm(), { url: `${ORIGIN}/api/share` }))).toBeNull();
+ expect(await worker.request(shareRequest(sharedForm(), { url: 'https://other.example/protocol/share' }))).toBeNull();
+ expect(await worker.request({ url: `${ORIGIN}/protocol/share`, mode: 'navigate', destination: 'document' } as never)).toBeNull();
+ expect(await caches.has(CACHE)).toBe(false);
+ });
+
+ it('leaves a POST into a hidden frame to the network: it stores nothing', async () => {
+ const caches = new FakeCaches();
+ await shellOn(caches, false);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await settle();
+ expect(await worker.request(shareRequest(sharedForm(), { destination: 'iframe' }))).toBeNull();
+ expect(await worker.request(shareRequest(sharedForm(), { destination: 'embed' }))).toBeNull();
+ expect(await caches.has(CACHE)).toBe(false);
+ });
+});
+
+describe('limits on what the worker keeps', () => {
+ it('drops the oldest entries over the entry limit, on every share', async () => {
+ const caches = new FakeCaches();
+ const now = Date.now();
+ for (let n = 0; n < 5; n += 1) await plantEntry(caches, `old-${n}`, now - 1000 * (5 - n));
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+
+ const answer = await worker.request(shareRequest(sharedForm()));
+
+ const ids = await entryIds(caches);
+ expect(ids).toHaveLength(5);
+ expect(ids).not.toContain('old-0');
+ expect(ids).toContain('old-1');
+ expect(ids).toContain(landingOf(answer).fragment.get('share'));
+ // Everything of the dropped one goes, not only its list.
+ expect(await (await caches.open(CACHE)).match('/__bulwark/handoff/old-0/sealed')).toBeUndefined();
+ });
+
+ it('drops the oldest entries over the byte limit', async () => {
+ const caches = new FakeCaches();
+ const now = Date.now();
+ await plantEntry(caches, 'big', now - 2000, 100 * 1024 * 1024 - 5);
+ await plantEntry(caches, 'small', now - 1000, 2);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+
+ await worker.request(shareRequest(sharedForm()));
+
+ const ids = await entryIds(caches);
+ expect(ids).not.toContain('big');
+ expect(ids).toContain('small');
+ });
+
+ it('stores nothing from a share over the byte limit, says the files are lost, and keeps the rest', async () => {
+ const caches = new FakeCaches();
+ await plantEntry(caches, 'kept', Date.now() - 1000, 10);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ const big = new File(['x'], 'huge.bin');
+ Object.defineProperty(big, 'size', { value: 100 * 1024 * 1024 + 1 });
+ const fields = new Map([['title', 'T']]);
+ const form = { get: (name: string) => fields.get(name) ?? null, getAll: () => [big] } as unknown as FormData;
+
+ const { fragment } = landingOf(await worker.request(shareRequest(form)));
+
+ expect(fragment.get('share')).toBe('unavailable');
+ expect(fragment.get('share_files')).toBe('1');
+ expect(await entryIds(caches)).toEqual(['kept']);
+ });
+
+ it('sweeps what is too old on every share', async () => {
+ const caches = new FakeCaches();
+ await plantEntry(caches, 'stale', Date.now() - TTL - 1);
+ await plantEntry(caches, 'fresh', Date.now() - 1000);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await worker.request(shareRequest(sharedForm()));
+ const ids = await entryIds(caches);
+ expect(ids).not.toContain('stale');
+ expect(ids).toContain('fresh');
+ });
+
+ it('sweeps what is too old when it activates', async () => {
+ const caches = new FakeCaches();
+ await plantEntry(caches, 'stale', Date.now() - TTL - 1);
+ await plantEntry(caches, 'fresh', Date.now() - 1000);
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await worker.dispatch('activate');
+ expect(await entryIds(caches)).toEqual(['fresh']);
+ });
+
+ it('creates no cache when it activates with nothing kept', async () => {
+ const caches = new FakeCaches();
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await worker.dispatch('activate');
+ expect(await caches.has(CACHE)).toBe(false);
+ });
+});
+
+describe('a mailto: launch without a connection', () => {
+ it('gets the kept handler page instead of a network error', async () => {
+ const caches = new FakeCaches();
+ await shellOn(caches, true);
+ const online = vi.fn(async () => htmlPage('mailto page'));
+ const worker = loadWorker({ buildId: 'a', caches, clients: [], fetch: online });
+ await settle();
+
+ await worker.dispatch('message', { data: { type: 'offline-shell', on: true, urls: ['/protocol/mailto'], buildId: 'a' } });
+ await settle();
+
+ online.mockImplementation(async () => { throw new TypeError('offline'); });
+ const answer = await worker.request({ url: `${ORIGIN}/protocol/mailto?url=mailto%3Aa%40example.org`, mode: 'navigate' });
+ expect(await answer!.text()).toBe('mailto page');
+ });
+
+ it('falls back to the start page when that page was never kept', async () => {
+ const caches = new FakeCaches();
+ await shellOn(caches, true);
+ const shell = await caches.open('bulwark-shell-a');
+ await shell.put(ORIGIN, htmlPage('start'));
+ const worker = loadWorker({ buildId: 'a', caches, clients: [] });
+ await settle();
+
+ const answer = await worker.request({ url: `${ORIGIN}/protocol/webcal?url=x`, mode: 'navigate' });
+ expect(await answer!.text()).toBe('start');
+ });
+});
diff --git a/lib/calendar-alerts.ts b/lib/calendar-alerts.ts
index bef0151e1..2c5e8ff96 100644
--- a/lib/calendar-alerts.ts
+++ b/lib/calendar-alerts.ts
@@ -7,7 +7,7 @@ import type {
Calendar,
CalendarTask,
} from '@/lib/jmap/types';
-import { parseDuration } from '@/components/calendar/event-card';
+import { parseDuration } from '@/lib/calendar-event-normalization';
export interface PendingAlert {
eventId: string;
diff --git a/lib/calendar-event-normalization.ts b/lib/calendar-event-normalization.ts
index 6dd31bf83..5305faa8e 100644
--- a/lib/calendar-event-normalization.ts
+++ b/lib/calendar-event-normalization.ts
@@ -39,6 +39,21 @@ export function parseDurationSeconds(duration: string | undefined): number | nul
return (((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + seconds;
}
+/** A duration in whole minutes, 0 when there is none. */
+export function parseDuration(duration: string | undefined): number {
+ if (!duration) return 0;
+ let totalMinutes = 0;
+ const weekMatch = duration.match(/(\d+)W/);
+ const hourMatch = duration.match(/(\d+)H/);
+ const minMatch = duration.match(/(\d+)M/);
+ const dayMatch = duration.match(/(\d+)D/);
+ if (weekMatch) totalMinutes += parseInt(weekMatch[1]) * 7 * 24 * 60;
+ if (dayMatch) totalMinutes += parseInt(dayMatch[1]) * 24 * 60;
+ if (hourMatch) totalMinutes += parseInt(hourMatch[1]) * 60;
+ if (minMatch) totalMinutes += parseInt(minMatch[1]);
+ return totalMinutes;
+}
+
export function normalizeAllDayDurationValue(duration: string | undefined): string | undefined {
const totalSeconds = parseDurationSeconds(duration);
if (totalSeconds === null || totalSeconds < 86400 || totalSeconds % 86400 !== 0) {
diff --git a/lib/calendar-utils.ts b/lib/calendar-utils.ts
index 2299fb54c..faff279c4 100644
--- a/lib/calendar-utils.ts
+++ b/lib/calendar-utils.ts
@@ -1,5 +1,5 @@
import { addDays, differenceInCalendarDays, parseISO, startOfDay, subMilliseconds } from "date-fns";
-import { parseDuration } from "@/components/calendar/event-card";
+import { parseDuration } from "@/lib/calendar-event-normalization";
import type { CalendarEvent } from "@/lib/jmap/types";
import { fromWallClock, isValidTimeZone, parseLocalDateTime, toDisplayDate } from "@/lib/timezone";
diff --git a/lib/deep-links.ts b/lib/deep-links.ts
index 483ad33a9..9e890e58e 100644
--- a/lib/deep-links.ts
+++ b/lib/deep-links.ts
@@ -137,7 +137,7 @@ const ALIASED_ROLES = new Set(['inbox', 'sent', 'drafts', 'trash', 'archive', 'j
*/
export type MailDeepLink =
| { kind: 'folder'; ref: string; accountId?: string; slot?: number; ownerAccountId?: string }
- | { kind: 'message'; id: string; accountId?: string; slot?: number; fullscreen?: boolean; ownerAccountId?: string }
+ | { kind: 'message'; id: string; accountId?: string; slot?: number; fullscreen?: boolean; ownerAccountId?: string; reply?: boolean }
| { kind: 'thread'; id: string; accountId?: string; slot?: number; ownerAccountId?: string };
export interface MailLinkState {
@@ -286,12 +286,15 @@ export function parseMailPath(
// opens message links as fullscreen email tabs and ignores the flag.
const fullscreen = search?.get('view') === 'fullscreen' || undefined;
const ownerAccountId = search?.get('owner') || undefined;
+ // `?reply=1`, a notification's Reply: opens the reply composer once. Only
+ // opens it: nothing a link says can send or change mail.
+ const reply = search?.get('reply') === '1' || undefined;
const [kind, value] = segments;
if (kind && value) {
const id = decodeSegment(value);
if (id) {
- if (kind === 'message') return { kind: 'message', id, accountId, slot, fullscreen, ownerAccountId };
+ if (kind === 'message') return { kind: 'message', id, accountId, slot, fullscreen, ownerAccountId, ...(reply ? { reply } : {}) };
if (kind === 'thread') return { kind: 'thread', id, accountId, slot, ownerAccountId };
if (kind === 'folder') return { kind: 'folder', ref: id, accountId, slot, ownerAccountId };
}
diff --git a/lib/global-search/__tests__/providers.test.ts b/lib/global-search/__tests__/providers.test.ts
index 111bf736c..fe54a5f7e 100644
--- a/lib/global-search/__tests__/providers.test.ts
+++ b/lib/global-search/__tests__/providers.test.ts
@@ -163,7 +163,7 @@ describe('mail provider', () => {
const result = await mailProvider.remote(parseSearchQuery('zebra'), account('login-a'), { limit: 25, signal });
expect(buildUnifiedAccountClients).toHaveBeenCalledWith({ includeGroup: true, scopeToClientAccountId: 'login-a' });
// The stub login has no trash/junk role folders, so no exclusion is added.
- expect(advancedSearchEmails).toHaveBeenCalledWith({ text: 'zebra' }, undefined, 25, 0);
+ expect(advancedSearchEmails).toHaveBeenCalledWith({ text: 'zebra' }, undefined, 25, 0, { palette: true });
expect(result.hasMore).toBe(true);
expect(result.hits[0]).toMatchObject({
id: 'm9', localAccountId: 'login-a', jmapAccountId: 'jmap-a', source: 'remote', subtitle: 'Inbox',
diff --git a/lib/global-search/providers/mail.ts b/lib/global-search/providers/mail.ts
index 14850795c..d52db2eab 100644
--- a/lib/global-search/providers/mail.ts
+++ b/lib/global-search/providers/mail.ts
@@ -119,6 +119,7 @@ export const mailProvider: SearchProvider = {
entry.isShared ? entry.jmapAccountId : undefined,
limit,
position,
+ { palette: true },
);
if (result.hasMore) hasMore = true;
for (const raw of result.emails) {
diff --git a/lib/jmap/__tests__/search-merge.test.ts b/lib/jmap/__tests__/search-merge.test.ts
new file mode 100644
index 000000000..4ef295281
--- /dev/null
+++ b/lib/jmap/__tests__/search-merge.test.ts
@@ -0,0 +1,903 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_SCOPE } from '@/lib/store/area';
+import { AccountEngine } from '@/lib/store/engine/account-engine';
+import { mailArea } from '@/lib/store/mail';
+import { FAKE_SESSION, FakeJmap, JMAP_ACCOUNT } from '@/lib/store/__tests__/helpers/fake-jmap';
+import { openMemoryStore } from '@/lib/store/__tests__/helpers/node-adapter';
+import { JMAPClient } from '../client';
+import type { SearchEmailsResult } from '../client-interface';
+import { setOfflineHooks, type OfflineHooks } from '../offline-hooks';
+import { filterHasTextTerms, LocalSearchMerge, mailboxesFitFilter } from '../search-merge';
+import type { Email } from '../types';
+
+function mail(id: string, minute: number, extra: Partial = {}): Email {
+ return { id, receivedAt: new Date(Date.UTC(2026, 9, 1, 0, minute)).toISOString(), ...extra } as Email;
+}
+
+/** A side of the search: the whole result list, answered a page at a time, newest first. */
+function side(rows: Email[], fixedTotal?: number) {
+ const asked: number[] = [];
+ const answer = async (position: number, limit: number): Promise => {
+ asked.push(position);
+ const total = fixedTotal ?? rows.length;
+ const emails = rows.slice(position, position + limit);
+ return { emails, total, hasMore: position + emails.length < total };
+ };
+ return { asked, answer };
+}
+
+function pager(server: ReturnType, local: ReturnType | null, limit: number) {
+ const merge = new LocalSearchMerge();
+ return (position: number) => merge.run({
+ key: 'search',
+ limit,
+ position,
+ server: (at) => server.answer(at, limit),
+ local: async (at) => (local ? local.answer(at, limit) : null),
+ });
+}
+
+const ids = (result: SearchEmailsResult) => result.emails.map((email) => email.id);
+
+describe('merging one page', () => {
+ it('sorts newest first and has no duplicates', async () => {
+ const server = side([mail('s4', 40), mail('both3', 30), mail('s1', 10)]);
+ const local = side([mail('l5', 50), mail('both3', 30), mail('l2', 20)]);
+ const result = await pager(server, local, 50)(0);
+ expect(ids(result)).toEqual(['l5', 's4', 'both3', 'l2', 's1']);
+ expect(result.hasMore).toBe(false);
+ expect(result.total).toBe(5);
+ });
+
+ it('keeps the server copy when both have a message', async () => {
+ const server = side([mail('both', 10, { subject: 'server copy' })]);
+ const local = side([mail('both', 10, { subject: 'local copy' })]);
+ const result = await pager(server, local, 50)(0);
+ expect(result.emails.map((email) => email.subject)).toEqual(['server copy']);
+ expect(result.total).toBe(1);
+ });
+
+ it('keeps the server copy when the local row sorts earlier than it', async () => {
+ // The local copy is out of date and looks newer: still one row, the server's.
+ const server = side([mail('s2', 20), mail('both', 10, { subject: 'server copy' })]);
+ const local = side([mail('both', 30, { subject: 'local copy' })]);
+ const result = await pager(server, local, 50)(0);
+ expect(ids(result)).toEqual(['s2', 'both']);
+ expect(result.emails[1].subject).toBe('server copy');
+ });
+
+ it('passes on what the server added to its result, such as its deferred snippets', async () => {
+ const snippets = Promise.resolve([]);
+ const merge = new LocalSearchMerge();
+ const result = await merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => ({ emails: [mail('s', 1)], total: 1, hasMore: false, snippets }),
+ local: async () => ({ emails: [mail('l', 2)], total: 1, hasMore: false }),
+ });
+ expect(result.snippets).toBe(snippets);
+ });
+});
+
+describe('paging', () => {
+ it('walks both lists with no row lost or repeated, counting by merged rows', async () => {
+ const serverRows = Array.from({ length: 25 }, (_, i) => mail(`s${i}`, 1000 - i * 10));
+ const localOnly = [mail('l-a', 995), mail('l-b', 905), mail('l-c', 805), mail('l-d', 500)];
+ const server = side(serverRows);
+ const local = side([...localOnly, serverRows[1], serverRows[12]].sort((a, b) => Date.parse(b.receivedAt) - Date.parse(a.receivedAt)));
+ const page = pager(server, local, 10);
+
+ const seen: string[] = [];
+ let result = await page(0);
+ seen.push(...ids(result));
+ expect(result.emails.length).toBe(10);
+ expect(result.hasMore).toBe(true);
+ let guard = 0;
+ while (result.hasMore && guard < 10) {
+ // As the store does: the next position is how many rows it holds.
+ result = await page(seen.length);
+ seen.push(...ids(result));
+ guard += 1;
+ }
+ expect(seen.length).toBe(29);
+ expect(new Set(seen).size).toBe(29);
+ expect(seen).toEqual(expect.arrayContaining([...serverRows.map((e) => e.id), ...localOnly.map((e) => e.id)]));
+ const times = [...serverRows, ...localOnly].sort((a, b) => Date.parse(b.receivedAt) - Date.parse(a.receivedAt)).map((e) => e.id);
+ expect(seen).toEqual(times);
+ expect(result.total).toBe(29);
+ });
+
+ it('asks the server for rows a local row pushed off the page', async () => {
+ const server = side([mail('s3', 30), mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l4', 40)]);
+ const page = pager(server, local, 2);
+ expect(ids(await page(0))).toEqual(['l4', 's3']);
+ expect(server.asked).toEqual([0]);
+ // Merged position 2, but the server has only given one row so far.
+ expect(ids(await page(2))).toEqual(['s2', 's1']);
+ expect(server.asked).toEqual([0, 1]);
+ });
+
+ it('holds back a local row older than what the server has sent, in case the server has it later', async () => {
+ const serverRows = [mail('s4', 40), mail('s3', 30), mail('both', 20), mail('s1', 10)];
+ const server = side(serverRows);
+ const local = side([mail('both', 20)]);
+ const page = pager(server, local, 2);
+ const first = await page(0);
+ expect(ids(first)).toEqual(['s4', 's3']);
+ const second = await page(2);
+ expect(ids(second)).toEqual(['both', 's1']);
+ expect(second.hasMore).toBe(false);
+ expect(second.total).toBe(4);
+ });
+
+ it('keeps paging through local rows when the server has none', async () => {
+ const server = side([]);
+ const local = side([mail('l3', 30), mail('l2', 20), mail('l1', 10)]);
+ const page = pager(server, local, 2);
+ const first = await page(0);
+ expect(ids(first)).toEqual(['l3', 'l2']);
+ expect(first.hasMore).toBe(true);
+ expect(first.total).toBe(3);
+ const second = await page(2);
+ expect(ids(second)).toEqual(['l1']);
+ expect(second.hasMore).toBe(false);
+ expect(second.total).toBe(3);
+ });
+
+ it('keeps total at or above what has been returned and what either side knows of', async () => {
+ const server = side([mail('s2', 20), mail('s1', 10)], 40);
+ const local = side([mail('l3', 30)], 50);
+ const result = await pager(server, local, 2)(0);
+ expect(result.total).toBe(50);
+ const noLocalLead = await pager(side([mail('s2', 20)], 40), side([mail('l3', 30)], 1), 2)(0);
+ expect(noLocalLead.total).toBe(41);
+ });
+
+ it('never repeats a local row the server later returns', async () => {
+ // Same time on both sides, split by the page edge: it shows once.
+ const server = side([mail('s', 20), mail('tie', 20)]);
+ const local = side([mail('tie', 20), mail('l', 5)]);
+ const page = pager(server, local, 1);
+ const seen = [...ids(await page(0))];
+ seen.push(...ids(await page(seen.length)));
+ seen.push(...ids(await page(seen.length)));
+ expect(seen).toEqual(['s', 'tie', 'l']);
+ });
+
+ it('drops a row the server returns later if the store already showed it, and holds older local rows until the server catches up', async () => {
+ // The local copy of x looks newer than the server's, so it goes out first.
+ const server = side([mail('a', 30), mail('b', 25), mail('x', 20), mail('c', 10)]);
+ const local = side([mail('x', 40), mail('l', 5)]);
+ const page = pager(server, local, 2);
+ const first = await page(0);
+ expect(ids(first)).toEqual(['x', 'a']);
+ // The server's page is b and x. x has been shown, and the server has more,
+ // so l can't be placed yet: it may be on the server's next page.
+ const second = await page(2);
+ expect(ids(second)).toEqual(['b']);
+ expect(second.hasMore).toBe(true);
+ const third = await page(3);
+ expect(ids(third)).toEqual(['c', 'l']);
+ expect(third.hasMore).toBe(false);
+ });
+
+ it('follows a caller whose position has moved since the last page', async () => {
+ const server = side([mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l5', 50)]);
+ const page = pager(server, local, 2);
+ await page(0);
+ // The caller added a row of its own to the list, as plugins can: one past.
+ await page(3);
+ expect(server.asked).toEqual([0, 2]);
+ });
+
+ it('starts over at position 0', async () => {
+ const server = side([mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l3', 30)]);
+ const page = pager(server, local, 2);
+ await page(0);
+ expect(ids(await page(0))).toEqual(['l3', 's2']);
+ });
+
+ it('walks a search again when it has no cursor, so no server row is skipped', async () => {
+ const server = side([mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l5', 50), mail('l25', 25)]);
+ const merge = new LocalSearchMerge();
+ const ask = (key: string, position: number) => merge.run({
+ key, limit: 2, position,
+ server: (at) => server.answer(at, 2),
+ local: (at) => local.answer(at, 2),
+ });
+ // The caller holds l5, s4, s3. As a merged position 3 would skip s2 on the server.
+ const result = await ask('evicted', 3);
+ expect(ids(result)).toEqual(['l25', 's2']);
+ });
+
+ it('sends a position with no cursor straight to the server when the store is off', async () => {
+ const server = side([mail('s2', 20), mail('s1', 10)]);
+ const result = await pager(server, null, 2)(1);
+ expect(ids(result)).toEqual(['s1']);
+ expect(server.asked).toEqual([0, 1]);
+ });
+
+ it('ends the list, and never guesses, past how far it will walk again', async () => {
+ const rows = Array.from({ length: 100 }, (_, i) => mail(`s${i}`, 1000 - i));
+ const server = side(rows);
+ const local = side([mail('l', 2000)]);
+ const result = await pager(server, local, 2)(90);
+ expect(result.emails).toEqual([]);
+ expect(result.hasMore).toBe(false);
+ expect(server.asked).not.toContain(90);
+ });
+
+ describe('a refresh of a longer list', () => {
+ function paged() {
+ const serverRows = [mail('s6', 60), mail('s5', 50), mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)];
+ const server = side(serverRows);
+ const local = side([mail('l7', 70)]);
+ return { server, local, page: pager(server, local, 2) };
+ }
+
+ it('leaves the next load-more where the list had got to', async () => {
+ const { page } = paged();
+ await page(0);
+ await page(2);
+ const refreshed = await page(0);
+ expect(ids(refreshed)).toEqual(['l7', 's6']);
+ const more = await page(4);
+ expect(ids(more)).toEqual(['s3', 's2']);
+ });
+
+ it('keeps total the same when nothing changed', async () => {
+ const { page } = paged();
+ const first = await page(0);
+ expect(first.total).toBe(7);
+ await page(2);
+ expect((await page(0)).total).toBe(7);
+ });
+
+ it('does not forget a local row that was on a later page', async () => {
+ const server = side([mail('s6', 60), mail('s5', 50), mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l45', 45)]);
+ const page = pager(server, local, 2);
+ expect(ids(await page(0))).toEqual(['s6', 's5']);
+ expect(ids(await page(2))).toEqual(['l45', 's4']);
+ // This first page has no local row, so it knows nothing of l45 by itself.
+ const refreshed = await page(0);
+ expect(ids(refreshed)).toEqual(['s6', 's5']);
+ expect(refreshed.total).toBe(7);
+ // The list holds four rows, three of them the server's: s3 is next.
+ const more = await page(4);
+ expect(ids(more)).toEqual(['s3', 's2']);
+ expect(more.total).toBe(7);
+ });
+
+ it('still lets a new search of the same words page from its own start', async () => {
+ const { page } = paged();
+ await page(0);
+ await page(2);
+ await page(0);
+ // The list was replaced by that page, so the next one starts right after it.
+ expect(ids(await page(2))).toEqual(['s5', 's4']);
+ });
+
+ it('moves on past a new row the refresh brought in', async () => {
+ const serverRows = [mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)];
+ const server = side(serverRows);
+ const local = side([mail('l5', 50)]);
+ const page = pager(server, local, 2);
+ await page(0);
+ await page(2);
+ serverRows.unshift(mail('new', 60));
+ const refreshed = await page(0);
+ expect(refreshed.total).toBe(6);
+ // The caller's list grew by one: l5 s4 s3 s2 plus the new row.
+ expect(ids(await page(5))).toEqual(['s1']);
+ });
+ });
+
+ describe('how long a cursor lasts', () => {
+ function search(merge: LocalSearchMerge, key: string, position: number, rows: ReturnType, local: ReturnType) {
+ return merge.run({ key, limit: 1, position, server: (at) => rows.answer(at, 1), local: (at) => local.answer(at, 1) });
+ }
+ const other = () => [side([mail('o', 1)]), side([])] as const;
+
+ it('keeps the search in use when many others come and go', async () => {
+ const merge = new LocalSearchMerge();
+ const server = side([mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l3', 30)]);
+ await search(merge, 'mine', 0, server, local);
+ for (let i = 0; i < 60; i += 1) await search(merge, `other-${i}`, 0, ...other());
+ await search(merge, 'mine', 1, server, local);
+ for (let i = 60; i < 120; i += 1) await search(merge, `other-${i}`, 0, ...other());
+ server.asked.length = 0;
+ expect(ids(await search(merge, 'mine', 2, server, local))).toEqual(['s1']);
+ // The cursor was there: no walking from the start again.
+ expect(server.asked).toEqual([1]);
+ });
+
+ it('still returns the right rows once a cursor is gone', async () => {
+ const merge = new LocalSearchMerge();
+ const server = side([mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l3', 30)]);
+ await search(merge, 'mine', 0, server, local);
+ for (let i = 0; i < 70; i += 1) await search(merge, `other-${i}`, 0, ...other());
+ expect(ids(await search(merge, 'mine', 1, server, local))).toEqual(['s2']);
+ });
+ });
+
+ it('counts a row both sides have once in total', async () => {
+ const server = side([mail('s1', 10)]);
+ const local = side([mail('s1', 10)]);
+ const result = await pager(server, local, 5)(0);
+ expect(result.total).toBe(1);
+ });
+
+ it('keeps searches apart by key', async () => {
+ const merge = new LocalSearchMerge();
+ const server = (rows: Email[]) => async (at: number) => ({ emails: rows.slice(at, at + 1), total: rows.length, hasMore: at + 1 < rows.length });
+ const a = { key: 'a', limit: 1, server: server([mail('a2', 20), mail('a1', 10)]), local: async () => ({ emails: [mail('la', 30)], total: 1, hasMore: false }) };
+ const b = { key: 'b', limit: 1, server: server([mail('b1', 10)]), local: async () => null };
+ expect(ids(await merge.run({ ...a, position: 0 }))).toEqual(['la']);
+ expect(ids(await merge.run({ ...b, position: 0 }))).toEqual(['b1']);
+ expect(ids(await merge.run({ ...a, position: 1 }))).toEqual(['a2']);
+ });
+});
+
+describe('rows only the store has', () => {
+ function run(
+ serverRows: Email[],
+ localRows: Email[],
+ verify: (rows: Email[]) => Promise,
+ limit = 5,
+ ) {
+ const server = side(serverRows);
+ const local = side(localRows);
+ return new LocalSearchMerge().run({
+ key: 'k', limit, position: 0,
+ server: (at) => server.answer(at, limit),
+ local: (at) => local.answer(at, limit),
+ verify,
+ });
+ }
+
+ it('drops what the server no longer has, and fills the page with the rest', async () => {
+ const verify = vi.fn(async (rows: Email[]) => rows.filter((row) => row.id !== 'deleted'));
+ const result = await run([mail('s1', 10)], [mail('deleted', 30), mail('kept', 20)], verify);
+ expect(ids(result)).toEqual(['kept', 's1']);
+ expect(result.total).toBe(2);
+ expect(verify.mock.calls[0][0].map((row) => row.id)).toEqual(['deleted', 'kept']);
+ });
+
+ it('shows the current copy of what the server still has', async () => {
+ const result = await run([], [mail('kept', 20, { subject: 'old', keywords: {} })], async () => [mail('kept', 20, { subject: 'current', keywords: { $seen: true } })]);
+ expect(result.emails[0].subject).toBe('current');
+ expect(result.emails[0].keywords).toEqual({ $seen: true });
+ });
+
+ it('marks them, so nothing takes them for new mail', async () => {
+ const result = await run([mail('s', 30)], [mail('s', 30), mail('kept', 20)], async (rows) => rows);
+ expect(result.emails.map((email) => email.foundLocally ?? false)).toEqual([false, true]);
+ });
+
+ it('does not ask when the store has nothing of its own', async () => {
+ const verify = vi.fn(async (rows: Email[]) => rows);
+ await run([mail('both', 10)], [mail('both', 10)], verify);
+ expect(verify).not.toHaveBeenCalled();
+ });
+
+ it('does not ask about a row too old for this page', async () => {
+ const verify = vi.fn(async (rows: Email[]) => rows);
+ await run([mail('s3', 30), mail('s2', 20), mail('s1', 10)], [mail('old', 5)], verify, 2);
+ expect(verify).not.toHaveBeenCalled();
+ });
+
+ it('keeps them when the check fails', async () => {
+ const result = await run([mail('s1', 10)], [mail('kept', 20)], async () => { throw new Error('offline again'); });
+ expect(ids(result)).toEqual(['kept', 's1']);
+ });
+
+ it('keeps them, unchecked, when the search itself failed', async () => {
+ const verify = vi.fn(async () => []);
+ const result = await new LocalSearchMerge().run({
+ key: 'k', limit: 5, position: 0,
+ server: async () => { throw new Error('server broke'); },
+ local: async () => ({ emails: [mail('kept', 20)], total: 1, hasMore: false }),
+ verify,
+ });
+ expect(ids(result)).toEqual(['kept']);
+ expect(verify).not.toHaveBeenCalled();
+ });
+});
+
+describe('mailboxesFitFilter', () => {
+ const inbox = { inbox: true };
+ it.each([
+ [{ inMailbox: 'inbox' }, inbox, true],
+ [{ inMailbox: 'inbox' }, { trash: true }, false],
+ [{ inMailbox: 'inbox' }, { inbox: false }, false],
+ [{ inMailbox: 'inbox' }, undefined, false],
+ [{ inMailboxOtherThan: ['trash', 'junk'] }, inbox, true],
+ [{ inMailboxOtherThan: ['trash', 'junk'] }, { trash: true }, false],
+ [{ inMailboxOtherThan: ['trash', 'junk'] }, { trash: true, inbox: true }, true],
+ [{ text: 'x' }, { trash: true }, true],
+ [{ operator: 'AND', conditions: [{ inMailbox: 'inbox' }, { text: 'x' }] }, { trash: true }, false],
+ [{ operator: 'AND', conditions: [{ inMailbox: 'inbox' }, { text: 'x' }] }, inbox, true],
+ [{ operator: 'OR', conditions: [{ inMailbox: 'a' }, { inMailbox: 'b' }] }, { b: true }, true],
+ [{ operator: 'OR', conditions: [{ inMailbox: 'a' }, { inMailbox: 'b' }] }, inbox, false],
+ [{ operator: 'OR', conditions: [{ inMailbox: 'a' }, { text: 'x' }] }, inbox, true],
+ [{ operator: 'NOT', conditions: [{ inMailbox: 'trash' }] }, inbox, true],
+ [{ operator: 'NOT', conditions: [{ inMailbox: 'trash' }] }, { trash: true }, false],
+ [{ operator: 'NOT', conditions: [{ text: 'x' }] }, inbox, true],
+ [{ inMailbox: 'trash', text: 'x' }, inbox, false],
+ ])('%j with %j is %s', (filter, boxes, expected) => {
+ expect(mailboxesFitFilter(filter, boxes as Record | undefined)).toBe(expected);
+ });
+});
+
+describe('errors', () => {
+ it('leaves no unhandled rejection when the store fails while the server is still working', async () => {
+ const unhandled: unknown[] = [];
+ const note = (reason: unknown) => { unhandled.push(reason); };
+ process.on('unhandledRejection', note);
+ try {
+ const result = await new LocalSearchMerge().run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ return { emails: [mail('s', 1)], total: 1, hasMore: false };
+ },
+ local: async () => { throw new Error('store broke'); },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(ids(result)).toEqual(['s']);
+ expect(unhandled).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', note);
+ }
+ });
+
+ it('keeps the list open when the server fails on a later page', async () => {
+ let fail = false;
+ const rows = side([mail('s4', 40), mail('s3', 30), mail('s2', 20), mail('s1', 10)]);
+ const local = side([mail('l5', 50), mail('l25', 25)]);
+ const merge = new LocalSearchMerge();
+ const run = (position: number) => merge.run({
+ key: 'k', limit: 2, position,
+ server: async (at) => {
+ if (fail) throw new Error('server broke');
+ return rows.answer(at, 2);
+ },
+ local: (at) => local.answer(at, 2),
+ });
+ expect((await run(0)).hasMore).toBe(true);
+ fail = true;
+ const during = await run(2);
+ expect(ids(during)).toEqual(['l25']);
+ // Local rows ran out, but the server said it had more: the list isn't over.
+ expect(during.hasMore).toBe(true);
+ fail = false;
+ expect(ids(await run(3))).toEqual(['s3', 's2']);
+ });
+
+ it('keeps the server result when the store fails', async () => {
+ const merge = new LocalSearchMerge();
+ const result = await merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => ({ emails: [mail('s', 1)], total: 1, hasMore: false }),
+ local: async () => { throw new Error('store broke'); },
+ });
+ expect(ids(result)).toEqual(['s']);
+ });
+
+ it('survives a store that fails before it can return a promise', async () => {
+ const merge = new LocalSearchMerge();
+ const result = await merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => ({ emails: [mail('s', 1)], total: 1, hasMore: false }),
+ local: () => { throw new Error('store broke'); },
+ });
+ expect(ids(result)).toEqual(['s']);
+ });
+
+ it('keeps the local result when the server fails', async () => {
+ const merge = new LocalSearchMerge();
+ const result = await merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => { throw new Error('server broke'); },
+ local: async () => ({ emails: [mail('l', 1)], total: 1, hasMore: false }),
+ });
+ expect(ids(result)).toEqual(['l']);
+ expect(result.total).toBe(1);
+ expect(result.hasMore).toBe(false);
+ });
+
+ it('asks the server again on the next page after it failed', async () => {
+ let fail = true;
+ const server = side([mail('s1', 10)]);
+ const merge = new LocalSearchMerge();
+ const run = (position: number) => merge.run({
+ key: 'k', limit: 1, position,
+ server: async (at) => {
+ if (fail) throw new Error('server broke');
+ return server.answer(at, 1);
+ },
+ local: async (at) => side([mail('l2', 20), mail('l1', 5)]).answer(at, 1),
+ });
+ expect(ids(await run(0))).toEqual(['l2']);
+ fail = false;
+ expect(ids(await run(1))).toEqual(['s1']);
+ });
+
+ it('keeps the server error when the store has nothing to show', async () => {
+ const failing = async () => { throw new Error('server broke'); };
+ await expect(new LocalSearchMerge().run({
+ key: 'k', limit: 10, position: 0, server: failing, local: async () => ({ emails: [], total: 0, hasMore: false }),
+ })).rejects.toThrow('server broke');
+ await expect(new LocalSearchMerge().run({
+ key: 'k', limit: 10, position: 0, server: failing, local: async () => null,
+ })).rejects.toThrow('server broke');
+ await expect(new LocalSearchMerge().run({
+ key: 'k', limit: 10, position: 0, server: failing, local: async () => { throw new Error('store broke too'); },
+ })).rejects.toThrow('server broke');
+ });
+
+ it('keeps the error of a later page, so the user can try again', async () => {
+ let fail = false;
+ const merge = new LocalSearchMerge();
+ const run = (position: number) => merge.run({
+ key: 'k', limit: 1, position,
+ server: async (at) => {
+ if (fail) throw new Error('server broke');
+ return side([mail('s2', 20), mail('s1', 10)]).answer(at, 1);
+ },
+ local: async (at) => side([mail('l3', 30)]).answer(at, 1),
+ });
+ expect(ids(await run(0))).toEqual(['l3']);
+ fail = true;
+ await expect(run(1)).rejects.toThrow('server broke');
+ fail = false;
+ expect(ids(await run(1))).toEqual(['s2']);
+ });
+
+ describe('with a store that never answers', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('counts the grace period from when the server answered', async () => {
+ const merge = new LocalSearchMerge();
+ let local: (value: SearchEmailsResult) => void = () => {};
+ const answer = merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+ return { emails: [mail('s', 1)], total: 1, hasMore: false };
+ },
+ local: () => new Promise((resolve) => { local = resolve; }),
+ });
+ await vi.advanceTimersByTimeAsync(5_000);
+ // The store answers soon after a slow server, and is still in time.
+ await vi.advanceTimersByTimeAsync(500);
+ local({ emails: [mail('l', 2)], total: 1, hasMore: false });
+ expect(ids(await answer)).toEqual(['l', 's']);
+ });
+
+ it('waits only as long as it was told to', async () => {
+ const merge = new LocalSearchMerge({ graceMs: 200 });
+ let done = false;
+ const answer = merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => ({ emails: [mail('s', 1)], total: 1, hasMore: false }),
+ local: () => new Promise(() => {}),
+ }).then((result) => {
+ done = true;
+ return result;
+ });
+ await vi.advanceTimersByTimeAsync(199);
+ expect(done).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(ids(await answer)).toEqual(['s']);
+ });
+
+ it('does not hold the server result back for long', async () => {
+ const merge = new LocalSearchMerge();
+ const answer = merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => ({ emails: [mail('s', 1)], total: 1, hasMore: false }),
+ local: () => new Promise(() => {}),
+ });
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(ids(await answer)).toEqual(['s']);
+ });
+
+ it('gives the server error once it has waited for the store', async () => {
+ const merge = new LocalSearchMerge();
+ const answer = merge.run({
+ key: 'k', limit: 10, position: 0,
+ server: async () => { throw new Error('server broke'); },
+ local: () => new Promise(() => {}),
+ });
+ const failed = expect(answer).rejects.toThrow('server broke');
+ await vi.advanceTimersByTimeAsync(5_000);
+ await failed;
+ });
+ });
+});
+
+describe('filterHasTextTerms', () => {
+ it('is true for searches for text, in any shape', () => {
+ for (const filter of [
+ { text: 'x' }, { from: 'x' }, { to: 'x' }, { cc: 'x' }, { bcc: 'x' }, { subject: 'x' }, { body: 'x' },
+ { operator: 'AND', conditions: [{ inMailbox: 'i' }, { text: 'x' }] },
+ { operator: 'OR', conditions: [{ to: 'x' }, { cc: 'x' }] },
+ { operator: 'AND', conditions: [{ operator: 'OR', conditions: [{ hasKeyword: 'a' }, { body: 'x' }] }] },
+ ]) expect(filterHasTextTerms(filter), JSON.stringify(filter)).toBe(true);
+ });
+
+ it('is false when nothing is searched for', () => {
+ for (const filter of [
+ {}, { inMailbox: 'i' }, { hasKeyword: '$seen' }, { text: '' }, { text: ' ' },
+ { operator: 'AND', conditions: [{ inMailbox: 'i' }, { hasAttachment: true }] },
+ { operator: 'NOT', conditions: [{ text: 'x' }] },
+ { operator: 'AND', conditions: [] },
+ ]) expect(filterHasTextTerms(filter), JSON.stringify(filter)).toBe(false);
+ });
+});
+
+describe('through the client, with a real store', () => {
+ const SERVER = 'https://mail.example.org';
+ const SESSION = {
+ apiUrl: `${SERVER}/jmap/`,
+ downloadUrl: `${SERVER}/jmap/download/{accountId}/{blobId}/{name}?accept={type}`,
+ uploadUrl: `${SERVER}/jmap/upload/{accountId}/`,
+ accounts: { [JMAP_ACCOUNT]: { name: 'alice', isPersonal: true, accountCapabilities: {} } },
+ primaryAccounts: { 'urn:ietf:params:jmap:mail': JMAP_ACCOUNT },
+ capabilities: { 'urn:ietf:params:jmap:core': { maxObjectsInGet: 500 } },
+ username: 'alice@example.org',
+ };
+
+ let serverRows: Array>;
+ let serverFails: boolean;
+ let requests: Array, string]>>;
+ /** What Email/get by id finds on the server, past the search's own rows. */
+ let serverKnows: Array>;
+
+ function fakeServerFetch() {
+ return vi.fn(async (url: string, init?: RequestInit) => {
+ if (String(url).endsWith('/.well-known/jmap')) return new Response(JSON.stringify(SESSION), { status: 200 });
+ const { methodCalls } = JSON.parse(String(init?.body)) as { methodCalls: Array<[string, Record, string]> };
+ requests.push(methodCalls);
+ if (serverFails) return new Response('broken', { status: 500 });
+ const [firstName, firstArgs, firstId] = methodCalls[0];
+ if (firstName === 'Email/get' && Array.isArray(firstArgs.ids)) {
+ const wanted = firstArgs.ids as string[];
+ const list = [...serverRows, ...serverKnows].filter((row) => wanted.includes(row.id as string));
+ return new Response(JSON.stringify({
+ methodResponses: [[firstName, { list, notFound: wanted.filter((id) => !list.some((row) => row.id === id)) }, firstId]],
+ }), { status: 200 });
+ }
+ const position = (methodCalls[0][1].position as number) ?? 0;
+ const limit = methodCalls[0][1].limit as number;
+ const page = serverRows.slice(position, position + limit);
+ return new Response(JSON.stringify({
+ methodResponses: methodCalls.map(([name, , id]) => {
+ if (name === 'Email/query') return [name, { ids: page.map((row) => row.id), total: serverRows.length, position }, id];
+ if (name === 'Email/get') return [name, { list: page, notFound: [] }, id];
+ return [name, { list: [], notFound: [] }, id];
+ }),
+ }), { status: 200 });
+ });
+ }
+
+ async function storeEngine() {
+ const fake = new FakeJmap();
+ fake.addEmail({ id: 'both', subject: 'Stromrechnung', receivedAt: '2026-10-05T00:00:00Z' });
+ fake.addEmail({ id: 'only-local', subject: 'Zahlungserinnerungsrechnung', receivedAt: '2026-10-03T00:00:00Z', mailboxIds: { inbox: true } });
+ fake.addEmail({ id: 'not-a-hit', subject: 'Hallo', receivedAt: '2026-10-02T00:00:00Z' });
+ const engine = new AccountEngine({
+ account: 'a@fake.test',
+ db: openMemoryStore(),
+ session: FAKE_SESSION,
+ transport: fake,
+ areas: [mailArea],
+ scope: { ...DEFAULT_SCOPE, days: null },
+ now: () => Date.UTC(2026, 10, 3),
+ sleep: async () => {},
+ });
+ await engine.requestSync();
+ return engine;
+ }
+
+ function hooksWith(searchLocal: OfflineHooks['searchLocal'], skipNetwork = false): OfflineHooks {
+ return {
+ skipNetwork: () => skipNetwork,
+ answer: async () => null,
+ record: () => {},
+ noteNetwork: () => {},
+ serverGone: async () => false,
+ blob: async () => null,
+ recordBlob: () => {},
+ holdUpload: async () => null,
+ searchLocal,
+ };
+ }
+
+ async function connected(): Promise {
+ const client = new JMAPClient(SERVER, 'alice@example.org', 'pw');
+ await client.connect();
+ return client;
+ }
+
+ beforeEach(() => {
+ serverFails = false;
+ requests = [];
+ serverKnows = [
+ { id: 'only-local', subject: 'Zahlungserinnerungsrechnung', receivedAt: '2026-10-03T00:00:00Z', mailboxIds: { inbox: true } },
+ ];
+ serverRows = [
+ { id: 'newer', subject: 'Rechnung', receivedAt: '2026-10-06T00:00:00Z', mailboxIds: { inbox: true } },
+ { id: 'both', subject: 'Stromrechnung, server copy', receivedAt: '2026-10-05T00:00:00Z', mailboxIds: { inbox: true } },
+ ];
+ vi.stubGlobal('fetch', fakeServerFetch());
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ setOfflineHooks(null);
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('merges what the store finds into searchEmails, with its highlights', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ const client = await connected();
+ const result = await client.searchEmails('rechnung');
+ expect(result.emails.map((email) => email.id)).toEqual(['newer', 'both', 'only-local']);
+ expect(result.emails[1].subject).toBe('Stromrechnung, server copy');
+ expect(result.emails[2].searchSnippet?.subject).toBe('Zahlungserinnerungsrechnung ');
+ expect(result.total).toBe(3);
+ expect(result.hasMore).toBe(false);
+ });
+
+ it('drops a row deleted on the server since the store last synced', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ serverKnows = [];
+ const client = await connected();
+ const result = await client.searchEmails('rechnung');
+ expect(result.emails.map((email) => email.id)).toEqual(['newer', 'both']);
+ expect(result.total).toBe(2);
+ });
+
+ it('drops a row moved out of the folder searched', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ serverKnows = [{ id: 'only-local', subject: 'x', receivedAt: '2026-10-03T00:00:00Z', mailboxIds: { trash: true } }];
+ const client = await connected();
+ const inFolder = await client.searchEmails('rechnung', 'inbox');
+ expect(inFolder.emails.map((email) => email.id)).toEqual(['newer', 'both']);
+ const everywhere = await client.searchEmails('rechnung');
+ expect(everywhere.emails.map((email) => email.id)).toEqual(['newer', 'both', 'only-local']);
+ const notInTrash = await client.advancedSearchEmails({ operator: 'AND', conditions: [{ text: 'rechnung' }, { inMailboxOtherThan: ['trash'] }] });
+ expect(notInTrash.emails.map((email) => email.id)).toEqual(['newer', 'both']);
+ });
+
+ it('searches the store without snippets, and asks only for those of its own rows', async () => {
+ const engine = await storeEngine();
+ const asked: string[][] = [];
+ const snippetIds: unknown[] = [];
+ setOfflineHooks(hooksWith((_client, calls) => {
+ asked.push(calls.map(([name]) => name));
+ for (const [name, args] of calls) if (name === 'SearchSnippet/get') snippetIds.push(args.emailIds);
+ return engine.answer(calls);
+ }));
+ const client = await connected();
+ await client.searchEmails('rechnung');
+ expect(asked).toEqual([['Email/query', 'Email/get'], ['SearchSnippet/get']]);
+ expect(snippetIds).toEqual([['only-local']]);
+ });
+
+ it('adds the snippets of its own rows to the deferred ones', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ const client = await connected();
+ const result = await client.searchEmails('rechnung', undefined, undefined, 50, 0, { deferSnippets: true });
+ expect(result.emails.every((email) => !email.searchSnippet)).toBe(true);
+ const snippets = await result.snippets;
+ expect(snippets?.find((s) => s.emailId === 'only-local')?.subject).toBe('Zahlungserinnerungsrechnung ');
+ });
+
+ it('keeps the palette from pushing out the paging of the mail list', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ const client = await connected();
+ await client.searchEmails('rechnung', undefined, undefined, 2);
+ for (let i = 0; i < 100; i += 1) await client.searchEmails(`wort${i}`, undefined, undefined, 2, 0, { palette: true });
+ requests = [];
+ await client.searchEmails('rechnung', undefined, undefined, 2, 2);
+ // With its cursor, the next page starts where the server left off, and nothing is walked again.
+ const queries = requests.flatMap((calls) => calls.filter(([name]) => name === 'Email/query'));
+ expect(queries.map(([, args]) => args.position)).toEqual([2]);
+ });
+
+ it('waits less for the store in the palette', async () => {
+ setOfflineHooks(hooksWith(() => new Promise(() => {})));
+ const client = await connected();
+ const started = Date.now();
+ const result = await client.searchEmails('rechnung', undefined, undefined, 50, 0, { palette: true });
+ expect(result.emails.length).toBe(2);
+ expect(Date.now() - started).toBeLessThan(900);
+ });
+
+ it('merges into advancedSearchEmails too, and leaves the server request as it was', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ const client = await connected();
+ const filter = { operator: 'AND', conditions: [{ inMailbox: 'inbox' }, { text: 'rechnung' }] };
+ const result = await client.advancedSearchEmails(filter);
+ expect(result.emails.map((email) => email.id)).toEqual(['newer', 'both', 'only-local']);
+ const query = requests[0][0];
+ expect(query[0]).toBe('Email/query');
+ expect(query[1]).toMatchObject({ filter, limit: 50, position: 0, calculateTotal: true, sort: [{ property: 'receivedAt', isAscending: false }] });
+ });
+
+ it('shows what the store found when the server fails', async () => {
+ const engine = await storeEngine();
+ setOfflineHooks(hooksWith((_client, calls) => engine.answer(calls)));
+ const client = await connected();
+ serverFails = true;
+ const result = await client.searchEmails('rechnung');
+ expect(result.emails.map((email) => email.id).sort()).toEqual(['both', 'only-local']);
+ });
+
+ it('shows what the server found when the store fails', async () => {
+ setOfflineHooks(hooksWith(async () => { throw new Error('store broke'); }));
+ const client = await connected();
+ const result = await client.searchEmails('rechnung');
+ expect(result.emails.map((email) => email.id)).toEqual(['newer', 'both']);
+ });
+
+ it('changes nothing when the store is off for the account', async () => {
+ const searchLocal = vi.fn(async () => null);
+ setOfflineHooks(hooksWith(searchLocal));
+ const client = await connected();
+ const result = await client.searchEmails('rechnung');
+ expect(searchLocal).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ emails: expect.any(Array), total: 2, hasMore: false });
+ expect(result.emails.map((email) => email.id)).toEqual(['newer', 'both']);
+ expect(requests.length).toBe(1);
+ });
+
+ it('changes nothing without a store', async () => {
+ setOfflineHooks(hooksWith(undefined));
+ const client = await connected();
+ const result = await client.searchEmails('rechnung', undefined, undefined, 50, 7);
+ expect(requests[0][0][1].position).toBe(7);
+ expect(result.total).toBe(2);
+ });
+
+ it('leaves filters without text to the server', async () => {
+ const searchLocal = vi.fn(async () => null);
+ setOfflineHooks(hooksWith(searchLocal));
+ const client = await connected();
+ await client.advancedSearchEmails({ inMailbox: 'inbox' });
+ await client.advancedSearchEmails({});
+ expect(searchLocal).not.toHaveBeenCalled();
+ });
+
+ it('does not ask twice when the device is answering anyway', async () => {
+ const searchLocal = vi.fn(async () => null);
+ const hooks = hooksWith(searchLocal, true);
+ hooks.answer = async (_client, calls) => ({
+ methodResponses: calls.map(([name, , id]) => (name === 'Email/query'
+ ? [name, { ids: [], total: 0, position: 0 }, id]
+ : [name, { list: [], notFound: [] }, id])),
+ });
+ setOfflineHooks(hooks);
+ const client = await connected();
+ await client.searchEmails('rechnung');
+ expect(searchLocal).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/jmap/client-interface.ts b/lib/jmap/client-interface.ts
index 377e61525..9b28a08eb 100644
--- a/lib/jmap/client-interface.ts
+++ b/lib/jmap/client-interface.ts
@@ -94,6 +94,11 @@ export interface SearchRequestOptions {
* where the list must not wait for the highlighting.
*/
deferSnippets?: boolean;
+ /**
+ * For the search palette. It searches on every few keystrokes, so it keeps its
+ * paging apart from the mail list's, and waits less for the local store.
+ */
+ palette?: boolean;
}
export interface SearchEmailsResult {
@@ -635,6 +640,8 @@ export interface IJMAPClient {
options?: CalendarEventUpdateOptions,
): Promise;
deleteCalendarEvent(eventId: string, sendSchedulingMessages?: boolean, targetAccountId?: string): Promise;
+ /** Whether the last request was answered from this device instead of the server. */
+ answeredFromDevice?(): boolean;
batchDeleteCalendarEvents(eventIds: string[], targetAccountId?: string): Promise<{ destroyed: string[]; notDestroyed: Record }>;
queryCalendarEvents(filter: CalendarEventFilter, sort?: Array<{ property: string; isAscending: boolean }>, limit?: number, targetAccountId?: string, options?: CalendarQueryOptions): Promise;
queryAllCalendarEvents(filter: CalendarEventFilter, sort?: Array<{ property: string; isAscending: boolean }>, limit?: number, options?: CalendarQueryOptions): Promise;
diff --git a/lib/jmap/client.ts b/lib/jmap/client.ts
index 5536ac710..1327f0aec 100644
--- a/lib/jmap/client.ts
+++ b/lib/jmap/client.ts
@@ -4,11 +4,13 @@ import { IncompleteDeleteError } from "./delete-error";
import { downloadAllowed, saveBlobAs, type DownloadKind } from "@/lib/download-guard";
import { ArchiveEmailsError } from "./archive-error";
import { generateUUID } from '@/lib/utils';
+import { standInsIn, withRealIds, withStandInsBack } from './stand-in-ids';
import type { Attachment, Email, Mailbox, MailboxRights, StateChange, AccountStates, CollectionChanges, ShareNotification, BusyPeriod, CalendarParticipantIdentity, CalendarEventNotification, Thread, Identity, EmailAddress, ContactCard, AddressBook, AddressBookRights, VacationResponse, Calendar, CalendarComponentType, CalendarRights, CalendarEvent, CalendarEventFilter, CalendarTask, CreateCalendarOptions, FileNode, FileNodeFilter, FileNodeRights, Principal, PrincipalAvailability, PrincipalListing, PushSubscription, EmailPushConfig, DeliveryStatus, EmailSubmission, RejectedRecipient, ScheduledEmail, SendEmailResult, SharedAccount } from "./types";
import type { SieveScript, SieveCapabilities } from "./sieve-types";
import type { BlobBatch, CalendarEventUpdateOptions, CalendarQueryOptions, FileNodeListings, IJMAPClient, KeywordDiscoveryResult, KeywordInfo, KeywordMigration, SearchEmailsResult, SearchRequestOptions, UploadedEmailImport, UploadedEmailImportResult } from "./client-interface";
import { attachSearchSnippets, filterHasSnippetTerms, snippetFilterFor, type SearchSnippetResult } from "@/lib/search-snippet";
import { textConditions, textFilter } from "./search-utils";
+import { filterHasTextTerms, LocalSearchMerge, mailboxesFitFilter } from "./search-merge";
import { batched, batchedBySize, itemsPerRequest } from "./request-limits";
import { keywordPointer, pointerToken } from "./patch-pointer";
import { FirstTouchGate } from "./first-touch-gate";
@@ -1638,6 +1640,8 @@ export class JMAPClient implements IJMAPClient {
* can be reached again (a reload signs in as usual).
*/
private offlineOnly = false;
+ private readonly searchMerge = new LocalSearchMerge();
+ private readonly paletteSearchMerge = new LocalSearchMerge({ graceMs: 200 });
constructor(serverUrl: string, username: string, password: string) {
this.serverUrl = serverUrl.replace(/\/$/, '');
@@ -2214,9 +2218,30 @@ export class JMAPClient implements IJMAPClient {
const offline = getOfflineHooks();
if (this.offlineOnly || offline?.skipNetwork(this)) {
const local = offline ? await offline.answer(this, methodCalls) : null;
- if (local) return local as JMAPResponse;
+ if (local) {
+ this.lastAnswerFromDevice = true;
+ return local as JMAPResponse;
+ }
throw new OfflineUnavailableError();
}
+ // A stand-in id from an event created offline, still held by an open dialog
+ // or a list: the server knows it by its real id, or not yet at all.
+ const standIns = offline?.resolveStandIns ? standInsIn(methodCalls) : [];
+ let realIds: Record | null = null;
+ if (standIns.length > 0) {
+ const resolved = await offline!.resolveStandIns!(this, standIns);
+ if (standIns.some((id) => !resolved[id])) {
+ const local = await offline!.answer(this, methodCalls);
+ if (local) {
+ this.lastAnswerFromDevice = true;
+ return local as JMAPResponse;
+ }
+ throw new OfflineUnavailableError();
+ }
+ realIds = resolved as Record;
+ methodCalls = withRealIds(methodCalls, realIds);
+ }
+ const asAsked = (response: JMAPResponse) => (realIds ? withStandInsBack(response, realIds) : response);
let answer: JMAPResponse;
try {
answer = await this.networkRequest(methodCalls, using, opts);
@@ -2225,15 +2250,25 @@ export class JMAPClient implements IJMAPClient {
// headers looks the same to the browser and must stay an error.
if (offline && isNetworkFailure(error) && await offline.serverGone(this)) {
const local = await offline.answer(this, methodCalls);
- if (local) return local as JMAPResponse;
+ if (local) {
+ this.lastAnswerFromDevice = true;
+ return asAsked(local as JMAPResponse);
+ }
}
throw error;
}
+ this.lastAnswerFromDevice = false;
if (offline) {
offline.noteNetwork(this, true);
if (!opts?.skipOfflineRecord) offline.record(this, methodCalls, answer);
}
- return answer;
+ return asAsked(answer);
+ }
+
+ private lastAnswerFromDevice = false;
+
+ answeredFromDevice(): boolean {
+ return this.lastAnswerFromDevice;
}
private async networkRequest(methodCalls: JMAPMethodCall[], using?: string[], opts?: { transfer?: boolean }): Promise {
@@ -4411,61 +4446,144 @@ export class JMAPClient implements IJMAPClient {
}
async searchEmails(query: string, mailboxId?: string, accountId?: string, limit: number = 50, position: number = 0, options: SearchRequestOptions = {}): Promise {
+ // The JMAP "text" filter searches from, to, cc, bcc, subject and body.
+ // Quoted phrases and `word*` prefixes go out as conditions of their
+ // own (see splitSearchText). inMailbox joins them in the same AND: a
+ // FilterOperator cannot also carry property keys.
+ const filter: Record = mailboxId
+ ? { operator: "AND", conditions: [{ inMailbox: mailboxId }, ...textConditions(query)] }
+ : textFilter(query);
+ return this.searchWithLocal(filter, accountId, limit, position, options);
+ }
+
+ /**
+ * A search on the server, merged with what the local store finds (see
+ * search-merge.ts). Without a store for this client, or when the request
+ * would be answered on this device anyway, it's the server's answer alone.
+ */
+ private searchWithLocal(
+ filter: Record,
+ accountId: string | undefined,
+ limit: number,
+ position: number,
+ options: SearchRequestOptions,
+ ): Promise {
+ const server = (at: number) => this.serverSearch(filter, accountId, limit, at, options);
+ const hooks = getOfflineHooks();
+ const searchLocal = hooks?.searchLocal;
+ if (!searchLocal || this.offlineOnly || hooks.skipNetwork(this) || !filterHasTextTerms(filter)) {
+ return server(position);
+ }
+ const targetAccountId = accountId || this.accountId;
+ const merge = options.palette ? this.paletteSearchMerge : this.searchMerge;
+ return merge.run({
+ key: JSON.stringify([accountId ?? null, filter]),
+ limit,
+ position,
+ server,
+ local: async (at) => {
+ // No snippets here: excerpting every hit is the slow part, and most of
+ // them are the server's to show. See localSnippets.
+ const answer = await searchLocal.call(hooks, this, this.searchCalls(targetAccountId, filter, limit, at, true));
+ return answer ? this.searchResultFrom(answer as JMAPResponse, accountId, limit, at) : null;
+ },
+ verify: (rows) => this.currentSearchRows(rows, filter, accountId),
+ localSnippets: async (ids) => {
+ if (!filterHasSnippetTerms(filter)) return null;
+ const answer = await searchLocal.call(hooks, this, [
+ ["SearchSnippet/get", { accountId: targetAccountId, filter: snippetFilterFor(filter), emailIds: ids }, "snippets"],
+ ]);
+ return answer ? this.searchSnippetsFrom(answer as JMAPResponse) ?? null : null;
+ },
+ deferSnippets: options.deferSnippets,
+ });
+ }
+
+ /**
+ * The server's copies of rows only the local store found, without those it
+ * no longer has or has outside the filter's folders. The filter is checked
+ * before the ids get their shared-account namespace, since it has bare ones.
+ */
+ private async currentSearchRows(rows: Email[], filter: Record, accountId: string | undefined): Promise {
+ const response = await this.request([
+ ["Email/get", {
+ accountId: accountId || this.accountId,
+ ids: rows.map((row) => row.id),
+ properties: [...EMAIL_LIST_PROPERTIES],
+ }, "0"],
+ ]);
+ const [name, result] = response.methodResponses?.[0] ?? [];
+ if (name !== "Email/get" || !result) throw new Error(methodErrorMessage(response, 'Failed to get emails'));
+ const list = applyListAuthenticationResults((result.list || []) as Email[])
+ .filter((email) => mailboxesFitFilter(filter, email.mailboxIds));
+ if (accountId && accountId !== this.accountId) namespaceMailboxIds(list, accountId);
+ return list;
+ }
+
+ private searchCalls(
+ targetAccountId: string,
+ filter: Record,
+ limit: number,
+ position: number,
+ deferSnippets: boolean | undefined,
+ ): JMAPMethodCall[] {
+ // Searching all folders with no criteria yields an empty FilterCondition,
+ // which servers reject; omit the key entirely to mean "no filter".
+ const hasFilter = Object.keys(filter).length > 0;
+ return [
+ ["Email/query", {
+ accountId: targetAccountId,
+ ...(hasFilter ? { filter } : {}),
+ sort: [{ property: "receivedAt", isAscending: false }],
+ limit,
+ position,
+ calculateTotal: true,
+ }, "0"],
+ ["Email/get", {
+ accountId: targetAccountId,
+ "#ids": { resultOf: "0", name: "Email/query", path: "/ids" },
+ properties: [...EMAIL_LIST_PROPERTIES],
+ }, "1"],
+ ...(deferSnippets ? [] : [this.searchSnippetCall(targetAccountId, hasFilter ? filter : undefined)]),
+ ];
+ }
+
+ private searchResultFrom(response: JMAPResponse, accountId: string | undefined, limit: number, position: number): SearchEmailsResult {
+ assertQuerySucceeded(response, 'Search');
+
+ const queryResponse = response.methodResponses?.[0]?.[1];
+ const emails = applyListAuthenticationResults((response.methodResponses?.[1]?.[1]?.list || []) as Email[]);
+ emails.sort((a: Email, b: Email) =>
+ new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime()
+ );
+ const total = queryResponse?.total || 0;
+ const hasMore = computeHasMore(position, emails.length, total, limit);
+ attachSearchSnippets(emails, this.searchSnippetsFrom(response));
+
+ // Mirror getEmails: emails fetched from a delegated/shared account carry
+ // bare owner mailbox ids; namespace them to `${ownerId}:${id}` so they line
+ // up with the namespaced ids the store holds for shared mailboxes. The
+ // cross-account views (All mail / Unread / Starred) browse via
+ // advancedSearchEmails, so they need this too. (#281 V3)
+ if (accountId && accountId !== this.accountId) {
+ namespaceMailboxIds(emails, accountId);
+ }
+ return { emails, hasMore, total };
+ }
+
+ private async serverSearch(
+ filter: Record,
+ accountId: string | undefined,
+ limit: number,
+ position: number,
+ options: SearchRequestOptions,
+ ): Promise {
try {
const targetAccountId = accountId || this.accountId;
-
- // The JMAP "text" filter searches from, to, cc, bcc, subject and body.
- // Quoted phrases and `word*` prefixes go out as conditions of their
- // own (see splitSearchText). inMailbox joins them in the same AND: a
- // FilterOperator cannot also carry property keys.
- let filter: Record;
- if (mailboxId) {
- filter = {
- operator: "AND",
- conditions: [
- { inMailbox: mailboxId },
- ...textConditions(query),
- ],
- };
- } else {
- filter = textFilter(query);
- }
-
- const response = await this.request([
- ["Email/query", {
- accountId: targetAccountId,
- filter,
- sort: [{ property: "receivedAt", isAscending: false }],
- limit,
- position,
- calculateTotal: true,
- }, "0"],
- ["Email/get", {
- accountId: targetAccountId,
- "#ids": { resultOf: "0", name: "Email/query", path: "/ids" },
- properties: [...EMAIL_LIST_PROPERTIES],
- }, "1"],
- ...(options.deferSnippets ? [] : [this.searchSnippetCall(targetAccountId, filter)]),
- ]);
- assertQuerySucceeded(response, 'Search');
-
- const queryResponse = response.methodResponses?.[0]?.[1];
- const emails = applyListAuthenticationResults((response.methodResponses?.[1]?.[1]?.list || []) as Email[]);
- emails.sort((a: Email, b: Email) =>
- new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime()
- );
- const total = queryResponse?.total || 0;
- const hasMore = computeHasMore(position, emails.length, total, limit);
- attachSearchSnippets(emails, this.searchSnippetsFrom(response));
-
- // Mirror getEmails: emails fetched from a delegated/shared account carry
- // bare owner mailbox ids; namespace them to `${ownerId}:${id}` so they line
- // up with the namespaced ids the store holds for shared mailboxes. (#281 V3)
- if (accountId && accountId !== this.accountId) {
- namespaceMailboxIds(emails, accountId);
- }
-
- return { emails, hasMore, total, ...this.deferredSnippets(options, targetAccountId, filter, emails) };
+ const hasFilter = Object.keys(filter).length > 0;
+ const response = await this.request(this.searchCalls(targetAccountId, filter, limit, position, options.deferSnippets));
+ const result = this.searchResultFrom(response, accountId, limit, position);
+ return { ...result, ...this.deferredSnippets(options, targetAccountId, hasFilter ? filter : undefined, result.emails) };
} catch (error) {
// Rethrow: an empty result would read as "No results found".
console.error('Search failed:', error);
@@ -4537,52 +4655,7 @@ export class JMAPClient implements IJMAPClient {
position: number = 0,
options: SearchRequestOptions = {},
): Promise {
- try {
- const targetAccountId = accountId || this.accountId;
-
- // Searching all folders with no criteria yields an empty FilterCondition,
- // which servers reject; omit the key entirely to mean "no filter".
- const hasFilter = Object.keys(filter).length > 0;
-
- const response = await this.request([
- ["Email/query", {
- accountId: targetAccountId,
- ...(hasFilter ? { filter } : {}),
- sort: [{ property: "receivedAt", isAscending: false }],
- limit,
- position,
- calculateTotal: true,
- }, "0"],
- ["Email/get", {
- accountId: targetAccountId,
- "#ids": { resultOf: "0", name: "Email/query", path: "/ids" },
- properties: [...EMAIL_LIST_PROPERTIES],
- }, "1"],
- ...(options.deferSnippets ? [] : [this.searchSnippetCall(targetAccountId, hasFilter ? filter : undefined)]),
- ]);
- assertQuerySucceeded(response, 'Search');
-
- const queryResponse = response.methodResponses?.[0]?.[1];
- const emails = applyListAuthenticationResults((response.methodResponses?.[1]?.[1]?.list || []) as Email[]);
- emails.sort((a: Email, b: Email) =>
- new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime()
- );
- const total = queryResponse?.total || 0;
- const hasMore = computeHasMore(position, emails.length, total, limit);
- attachSearchSnippets(emails, this.searchSnippetsFrom(response));
-
- // Namespace shared/delegated-account mailbox ids (see searchEmails). The
- // cross-account views (All mail / Unread / Starred) browse via this method,
- // so without it shared emails would carry bare owner ids there. (#281 V3)
- if (accountId && accountId !== this.accountId) {
- namespaceMailboxIds(emails, accountId);
- }
-
- return { emails, hasMore, total, ...this.deferredSnippets(options, targetAccountId, hasFilter ? filter : undefined, emails) };
- } catch (error) {
- console.error('Advanced search failed:', error);
- throw error;
- }
+ return this.searchWithLocal(filter, accountId, limit, position, options);
}
async getEmailFields(
@@ -9437,6 +9510,8 @@ export class JMAPClient implements IJMAPClient {
// Strip client-only shared fields before sending to JMAP
const { originalId: _oi, baseEventId: _be, originalCalendarIds: _oc, accountId: _ai, accountName: _an, isShared: _is, ...cleanEvent } = event as CalendarEvent;
cleanRecurrenceRules(cleanEvent as unknown as Record);
+ // Chosen here, not by the server: if the answer is lost, this finds the event again.
+ cleanEvent.uid ||= generateUUID();
debug.group('CalendarEvent/create', 'calendar');
debug.log('calendar', 'CalendarEvent/create outgoing payload', {
@@ -9543,6 +9618,7 @@ export class JMAPClient implements IJMAPClient {
for (const { event, index } of batch) {
const { originalId: _oi, originalCalendarIds: _oc, accountId: _ai, accountName: _an, isShared: _is, ...clean } = event as CalendarEvent;
cleanRecurrenceRules(clean as unknown as Record);
+ clean.uid ||= generateUUID();
createMap[`new-${index}`] = clean;
}
@@ -9967,7 +10043,7 @@ export class JMAPClient implements IJMAPClient {
accountId = resolved.accountId;
taskData.calendarIds = resolved.calendarIds;
}
- const cleanTask = { ...completeBareTaskDates(taskData), '@type': 'Task' };
+ const cleanTask = { ...completeBareTaskDates(taskData), '@type': 'Task', uid: taskData.uid || generateUUID() };
debug.group('CalendarTask/create', 'tasks');
debug.log('tasks', 'CalendarTask/create accountId', accountId);
diff --git a/lib/jmap/offline-hooks.ts b/lib/jmap/offline-hooks.ts
index ab0477fc9..ab746f3bc 100644
--- a/lib/jmap/offline-hooks.ts
+++ b/lib/jmap/offline-hooks.ts
@@ -45,6 +45,18 @@ export interface OfflineHooks {
recordBlob(client: OfflineClientRef, blobId: string, accountId: string, blob: Blob): void;
/** Keep a file to upload later; the stand-in blob id, or null when offline mode doesn't cover the client. */
holdUpload(client: OfflineClientRef, file: File, accountId: string): Promise<{ blobId: string; size: number; type: string } | null>;
+ /**
+ * Search calls answered from the local store while the server is asked too
+ * (lib/jmap/search-merge.ts). Null when the store doesn't cover the client.
+ * Left out when there is no store, and searches then go to the server alone.
+ */
+ searchLocal?(client: OfflineClientRef, methodCalls: OfflineMethodCall[]): Promise;
+ /**
+ * Real ids for stand-in ids the page still holds (lib/jmap/stand-in-ids.ts), or
+ * null for one that hasn't reached the server yet. Without it the client sends
+ * ids as they are.
+ */
+ resolveStandIns?(client: OfflineClientRef, ids: string[]): Promise>;
}
const KEY = '__bulwarkOfflineHooks';
diff --git a/lib/jmap/search-merge.ts b/lib/jmap/search-merge.ts
new file mode 100644
index 000000000..a7200b0f9
--- /dev/null
+++ b/lib/jmap/search-merge.ts
@@ -0,0 +1,382 @@
+/**
+ * Online, a search also asks the local store and merges the two answers. The
+ * store finds what the server's index can't, such as a word inside a German
+ * compound. This module knows nothing about the store: it merges two lists.
+ *
+ * The merge walks both lists newest first, as a search sorts them. When both
+ * have a message, the server's copy is kept. A page never holds more than
+ * `limit` rows, so a local row can push a server row to the next page.
+ *
+ * A row only the store has may be stale: deleted or moved since the store last
+ * synced. So the server is asked for those rows before they're shown. What it
+ * no longer has, or has outside the filter's folders, is dropped, and what it
+ * still has is shown as its current copy. It takes a request of its own, since
+ * these ids are only known once both answers are in. If that request fails, or
+ * the search itself did, the rows stay: an error must not lose results.
+ *
+ * Callers page by counting the rows they have, so `position` counts merged
+ * rows and means nothing to the server once a local row is among them. A cursor
+ * for each search remembers how far each side was read:
+ * - Position 0 can be a new search or a refresh of a longer list, and only the
+ * next page tells which. So it runs on a cursor of its own next to the one
+ * already there. The next page takes whichever ended closest to its position.
+ * - With no cursor (it was evicted), the search is walked again from the start
+ * up to the position. A merged position never goes to the server as it is.
+ * - When the store has nothing to say for this search, no merged row exists and
+ * positions are the server's own, so requests pass straight through.
+ *
+ * `hasMore` is true while either side has rows this search hasn't returned.
+ * A local list made only of rows the server also has can therefore cost one
+ * extra page that comes back empty, and then it's false. When the server fails
+ * on a later page, what it last said about having more still counts.
+ *
+ * `total` is the server's total plus the local-only rows returned so far, and
+ * never less than the local total or the rows already returned. It can grow
+ * while paging, because how many local rows the server also has only shows
+ * when the lists are read.
+ *
+ * Local rows older than the last row the server sent wait for the next page:
+ * they may still be on the server's next page.
+ *
+ * An error on one side keeps the other side's rows. When the server fails and
+ * the store has nothing, the server's error stands, since an empty list would
+ * read as "no results". A slow store holds up the server's answer for at most
+ * the grace period, counted from when the server answered. Snippets for local
+ * rows are asked for separately, so excerpting bodies in the worker doesn't
+ * hold up the list either.
+ */
+
+import { debug } from '@/lib/debug';
+import { attachSearchSnippets, type SearchSnippetResult } from '@/lib/search-snippet';
+import type { SearchEmailsResult } from './client-interface';
+import type { Email } from './types';
+
+const LOCAL_GRACE_MS = 1_000;
+const LOCAL_ALONE_MS = 5_000;
+const MAX_CURSORS = 64;
+/** How far back an evicted search is walked again. Past this, the list ends. */
+const MAX_WALK_PAGES = 20;
+
+const TEXT_FILTER_KEYS = ['text', 'from', 'to', 'cc', 'bcc', 'subject', 'body'];
+
+/**
+ * Whether a filter searches for text. Other filters (a folder, a flag, a date)
+ * have the same answer on both sides, so only a stale local row could come of
+ * merging them. Terms under NOT are searched to be absent, so they don't count.
+ */
+export function filterHasTextTerms(filter: Record): boolean {
+ if (typeof filter.operator === 'string') {
+ if (filter.operator === 'NOT' || !Array.isArray(filter.conditions)) return false;
+ return (filter.conditions as Array>).some(filterHasTextTerms);
+ }
+ return TEXT_FILTER_KEYS.some((key) => typeof filter[key] === 'string' && (filter[key] as string).trim().length > 0);
+}
+
+/** True, false, or null when the filter's answer depends on more than the folders. */
+function mailboxAnswer(filter: Record, boxes: readonly string[]): boolean | null {
+ if (typeof filter.operator === 'string') {
+ const answers = (Array.isArray(filter.conditions) ? filter.conditions as Array> : [])
+ .map((condition) => mailboxAnswer(condition, boxes));
+ const unknown = answers.includes(null);
+ if (filter.operator === 'AND') return answers.includes(false) ? false : unknown ? null : true;
+ const any = answers.includes(true) ? true : unknown ? null : false;
+ if (filter.operator === 'OR') return any;
+ if (filter.operator === 'NOT') return any === null ? null : !any;
+ return null;
+ }
+ const answers: boolean[] = [];
+ if (typeof filter.inMailbox === 'string') answers.push(boxes.includes(filter.inMailbox));
+ if (Array.isArray(filter.inMailboxOtherThan)) {
+ const excluded = filter.inMailboxOtherThan as string[];
+ answers.push(boxes.some((box) => !excluded.includes(box)));
+ }
+ if (answers.includes(false)) return false;
+ return answers.length > 0 && Object.keys(filter).length === answers.length ? true : null;
+}
+
+/** Whether a message's folders still fit the filter. Conditions on anything else don't count against it. */
+export function mailboxesFitFilter(filter: Record, mailboxIds: Record | undefined): boolean {
+ const boxes = Object.entries(mailboxIds ?? {}).filter(([, on]) => on).map(([id]) => id);
+ return mailboxAnswer(filter, boxes) !== false;
+}
+
+interface MergeCursor {
+ /** Merged rows returned so far, which is where the next page should ask from. */
+ next: number;
+ serverPosition: number;
+ localPosition: number;
+ serverTotal: number;
+ serverHasMore: boolean;
+ /** Local-only rows returned so far. */
+ extras: number;
+ /** Local rows the server said are gone. */
+ rejected: number;
+ /** Every row returned so far, so none appears twice. */
+ shown: Set;
+ /** The store has nothing for this search: positions are the server's. */
+ passthrough: boolean;
+}
+
+function newCursor(): MergeCursor {
+ return {
+ next: 0, serverPosition: 0, localPosition: 0, serverTotal: 0, serverHasMore: false,
+ extras: 0, rejected: 0, shown: new Set(), passthrough: false,
+ };
+}
+
+interface CursorEntry {
+ cursor: MergeCursor;
+ /** A position 0 that came after later pages: a new search or a refresh. */
+ restarted: MergeCursor | null;
+}
+
+function receivedTime(email: Email): number {
+ return Date.parse(email.receivedAt) || 0;
+}
+
+interface PageMerge {
+ emails: Email[];
+ serverRead: number;
+ localRead: number;
+ extraIds: string[];
+}
+
+/** One merged page. Rows are added to `shown`. */
+export function mergeSearchPages(
+ server: readonly Email[],
+ serverHasMore: boolean,
+ local: readonly Email[],
+ limit: number,
+ shown: Set,
+): PageMerge {
+ const serverIds = new Set(server.map((email) => email.id));
+ const emails: Email[] = [];
+ const extraIds: string[] = [];
+ let s = 0;
+ let l = 0;
+ while (emails.length < limit) {
+ const fromServer = server[s];
+ const fromLocal = local[l];
+ if (fromLocal && (serverIds.has(fromLocal.id) || shown.has(fromLocal.id))) {
+ l += 1;
+ continue;
+ }
+ if (fromServer && shown.has(fromServer.id)) {
+ s += 1;
+ continue;
+ }
+ if (!fromServer && (!fromLocal || serverHasMore)) break;
+ if (fromServer && (!fromLocal || receivedTime(fromLocal) <= receivedTime(fromServer))) {
+ emails.push(fromServer);
+ shown.add(fromServer.id);
+ s += 1;
+ } else {
+ emails.push({ ...fromLocal, foundLocally: true });
+ shown.add(fromLocal.id);
+ extraIds.push(fromLocal.id);
+ l += 1;
+ }
+ }
+ return { emails, serverRead: s, localRead: l, extraIds };
+}
+
+/** The promise's value, or null if it takes longer than `ms`. The promise must not reject. */
+function within(promise: Promise, ms: number): Promise {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(null), ms);
+ void promise.then((value) => {
+ clearTimeout(timer);
+ resolve(value);
+ });
+ });
+}
+
+/** Runs a store call with its failure handled right away, so it can't go unhandled while the server is awaited. */
+function safely(what: string, call: () => Promise): Promise {
+ return Promise.resolve().then(call).catch((error: unknown) => {
+ debug.warn('jmap', `${what} failed:`, error);
+ return null;
+ });
+}
+
+export interface MergedSearchRequest {
+ /** The same for every page of one search. */
+ key: string;
+ limit: number;
+ position: number;
+ server(position: number): Promise;
+ /** Null when the store doesn't cover this account. */
+ local(position: number): Promise;
+ /** The server's current copies of these rows, leaving out what's gone or no longer fits the search. */
+ verify?(rows: Email[]): Promise;
+ /** Highlights for rows only the store has. */
+ localSnippets?(ids: string[]): Promise;
+ /** Hand local snippets back as `snippets` instead of waiting for them. */
+ deferSnippets?: boolean;
+}
+
+export interface LocalSearchMergeOptions {
+ /** How long a slow store may hold up the server's answer. */
+ graceMs?: number;
+}
+
+export class LocalSearchMerge {
+ private readonly cursors = new Map();
+ private readonly graceMs: number;
+
+ constructor(options: LocalSearchMergeOptions = {}) {
+ this.graceMs = options.graceMs ?? LOCAL_GRACE_MS;
+ }
+
+ /** Least recently used goes first, so a search being paged through stays. */
+ private remember(key: string, entry: CursorEntry): void {
+ this.cursors.delete(key);
+ this.cursors.set(key, entry);
+ if (this.cursors.size > MAX_CURSORS) this.cursors.delete(this.cursors.keys().next().value as string);
+ }
+
+ async run(request: MergedSearchRequest): Promise {
+ const { key, limit, position } = request;
+ const entry = this.cursors.get(key);
+ if (position === 0) {
+ const fresh = newCursor();
+ const alongside = entry && entry.cursor.next > 0 ? entry.cursor : null;
+ this.remember(key, alongside ? { cursor: alongside, restarted: fresh } : { cursor: fresh, restarted: null });
+ return this.page(fresh, request, 0, limit, { alongside });
+ }
+ if (!entry) return this.walkTo(request);
+ this.remember(key, entry);
+ const cursor = this.choose(entry, position);
+ if (cursor.passthrough) return request.server(position);
+ return this.page(cursor, request, position, limit, {});
+ }
+
+ /** Which cursor the page after a position 0 continues from. Only that one is kept from then on. */
+ private choose(entry: CursorEntry, position: number): MergeCursor {
+ const { cursor, restarted } = entry;
+ if (!restarted) return cursor;
+ entry.restarted = null;
+ const restartedIsCloser = Math.abs(position - restarted.next) <= Math.abs(position - cursor.next);
+ if (cursor.passthrough || restartedIsCloser) {
+ entry.cursor = restarted;
+ return restarted;
+ }
+ for (const id of restarted.shown) cursor.shown.add(id);
+ return cursor;
+ }
+
+ /** No cursor: read the search again from the start, so the rows the caller holds are accounted for. */
+ private async walkTo(request: MergedSearchRequest): Promise {
+ const { key, limit, position } = request;
+ const cursor = newCursor();
+ let last: SearchEmailsResult | null = null;
+ for (let page = 0; cursor.next < position && !cursor.passthrough; page += 1) {
+ if (page === MAX_WALK_PAGES) return { emails: [], hasMore: false, total: last?.total ?? position };
+ last = await this.page(cursor, request, cursor.next, Math.min(limit, position - cursor.next), { walking: true });
+ if (last.emails.length === 0 || !last.hasMore) break;
+ }
+ this.remember(key, { cursor, restarted: null });
+ if (cursor.passthrough) return request.server(position);
+ // The search ended before the position: the caller holds rows that are gone.
+ cursor.next = position;
+ return this.page(cursor, request, position, limit, {});
+ }
+
+ private async page(
+ cursor: MergeCursor,
+ request: MergedSearchRequest,
+ position: number,
+ limit: number,
+ { alongside = null, walking = false }: { alongside?: MergeCursor | null; walking?: boolean },
+ ): Promise {
+ // A caller that removed rows or added its own asks from a little off
+ // where the last page ended, and the server's side moves with it.
+ const serverPosition = Math.max(0, cursor.serverPosition + position - cursor.next);
+ const localAnswer = safely('Local search', () => request.local(cursor.localPosition));
+
+ let serverPage: SearchEmailsResult | null = null;
+ let serverError: unknown = null;
+ try {
+ serverPage = await request.server(serverPosition);
+ } catch (error) {
+ serverError = error;
+ }
+ const localPage = await within(localAnswer, serverPage ? this.graceMs : LOCAL_ALONE_MS);
+
+ if (!serverPage && !localPage?.emails.length) throw serverError;
+ if (serverPage && !localPage && cursor.extras === 0) {
+ // Nothing local in this search: the server's answer, untouched.
+ cursor.passthrough = true;
+ cursor.next = position + serverPage.emails.length;
+ return serverPage;
+ }
+
+ const server = serverPage?.emails ?? [];
+ const serverHasMore = serverPage?.hasMore ?? false;
+ const local = serverPage
+ ? await this.verified(request, cursor, server, serverHasMore, localPage?.emails ?? [])
+ : localPage?.emails ?? [];
+ const merged = mergeSearchPages(server, serverHasMore, local, limit, cursor.shown);
+
+ cursor.serverPosition = serverPosition + merged.serverRead;
+ cursor.localPosition += merged.localRead;
+ cursor.next = position + merged.emails.length;
+ cursor.extras += merged.extraIds.length;
+ if (serverPage) {
+ cursor.serverTotal = serverPage.total;
+ cursor.serverHasMore = merged.serverRead < server.length || serverHasMore;
+ }
+
+ const localLeft = localPage ? merged.localRead < local.length || localPage.hasMore : false;
+ // A refresh of a longer list counts the local rows already in that list.
+ const extras = Math.max(cursor.extras, alongside?.extras ?? 0);
+ const rejected = Math.max(cursor.rejected, alongside?.rejected ?? 0);
+ const result: SearchEmailsResult = {
+ ...serverPage,
+ emails: merged.emails,
+ hasMore: cursor.serverHasMore || localLeft,
+ total: Math.max(cursor.serverTotal + extras, (localPage?.total ?? 0) - rejected, cursor.next),
+ };
+ if (!walking && merged.extraIds.length > 0 && request.localSnippets) await this.addLocalSnippets(request, merged, result);
+ return result;
+ }
+
+ /** The local rows, with what the server no longer has marked as read past, and the rest as its current copies. */
+ private async verified(
+ request: MergedSearchRequest,
+ cursor: MergeCursor,
+ server: readonly Email[],
+ serverHasMore: boolean,
+ local: Email[],
+ ): Promise {
+ if (!request.verify) return local;
+ const serverIds = new Set(server.map((email) => email.id));
+ const oldestPlaceable = serverHasMore && server.length > 0 ? receivedTime(server[server.length - 1]) : -Infinity;
+ const candidates = local.filter((row) => !serverIds.has(row.id) && !cursor.shown.has(row.id) && receivedTime(row) >= oldestPlaceable);
+ if (candidates.length === 0) return local;
+ let current: Email[];
+ try {
+ current = await request.verify(candidates);
+ } catch (error) {
+ debug.warn('jmap', 'Checking local search results failed:', error);
+ return local;
+ }
+ const byId = new Map(current.map((row) => [row.id, row]));
+ for (const row of candidates) {
+ if (byId.has(row.id)) continue;
+ cursor.shown.add(row.id);
+ cursor.rejected += 1;
+ }
+ return local.map((row) => byId.get(row.id) ?? row);
+ }
+
+ private async addLocalSnippets(request: MergedSearchRequest, merged: PageMerge, result: SearchEmailsResult): Promise {
+ const asked = safely('Local snippets', () => (request.localSnippets as NonNullable)(merged.extraIds));
+ if (!request.deferSnippets) {
+ attachSearchSnippets(result.emails, (await within(asked, this.graceMs)) ?? undefined);
+ return;
+ }
+ const fromServer = result.snippets;
+ result.snippets = Promise.all([fromServer, asked]).then(([a, b]) => (a || b ? [...(a ?? []), ...(b ?? [])] : undefined));
+ }
+}
diff --git a/lib/jmap/stand-in-ids.ts b/lib/jmap/stand-in-ids.ts
new file mode 100644
index 000000000..00da263e6
--- /dev/null
+++ b/lib/jmap/stand-in-ids.ts
@@ -0,0 +1,76 @@
+/**
+ * Stand-in ids: what the local store hands out for an event created offline.
+ *
+ * A page can hold one long after the event reached the server: an open dialog,
+ * a list not refetched yet, a plugin. So the client swaps them for the real ids
+ * on the way to the network, and swaps them back in the answer, because callers
+ * look up the outcome under the id they asked about.
+ */
+
+import type { OfflineMethodCall, OfflineResponse } from './offline-hooks';
+
+const STAND_IN_PREFIX = 'local-';
+
+export function isStandInId(id: string): boolean {
+ return id.startsWith(STAND_IN_PREFIX);
+}
+
+export function newStandInId(): string {
+ return `${STAND_IN_PREFIX}${crypto.randomUUID()}`;
+}
+
+/** The stand-in ids a request names. */
+export function standInsIn(calls: readonly OfflineMethodCall[]): string[] {
+ const found = new Set();
+ for (const [name, args] of calls) {
+ if (name === 'CalendarEvent/set') {
+ for (const id of Object.keys((args.update ?? {}) as object)) if (isStandInId(id)) found.add(id);
+ for (const id of (args.destroy ?? []) as string[]) if (isStandInId(id)) found.add(id);
+ } else if (name === 'CalendarEvent/get') {
+ for (const id of (args.ids ?? []) as string[]) if (isStandInId(id)) found.add(id);
+ }
+ }
+ return [...found];
+}
+
+function renamedKeys(map: Record, rename: (id: string) => string): Record {
+ return Object.fromEntries(Object.entries(map).map(([id, value]) => [rename(id), value]));
+}
+
+/** The request with every stand-in swapped for its real id. */
+export function withRealIds(calls: readonly T[], real: Readonly>): T[] {
+ const rename = (id: string) => real[id] ?? id;
+ return calls.map((call) => {
+ const [name, args, callId] = call;
+ if (name === 'CalendarEvent/set') {
+ const next = { ...args };
+ if (args.update) next.update = renamedKeys(args.update as Record, rename);
+ if (args.destroy) next.destroy = (args.destroy as string[]).map(rename);
+ return [name, next, callId] as unknown as T;
+ }
+ if (name === 'CalendarEvent/get' && args.ids) {
+ return [name, { ...args, ids: (args.ids as string[]).map(rename) }, callId] as unknown as T;
+ }
+ return call;
+ });
+}
+
+/** The answer as if the caller's ids had gone out. The objects in a get's list keep their real id. */
+export function withStandInsBack(response: T, real: Readonly>): T {
+ const back = new Map(Object.entries(real).map(([standIn, id]) => [id, standIn]));
+ const rename = (id: string) => back.get(id) ?? id;
+ return {
+ ...response,
+ methodResponses: response.methodResponses.map(([name, result, callId]) => {
+ if (name !== 'CalendarEvent/set' && name !== 'CalendarEvent/get') return [name, result, callId];
+ const next = { ...result };
+ for (const key of ['updated', 'notUpdated', 'notDestroyed']) {
+ if (next[key]) next[key] = renamedKeys(next[key], rename);
+ }
+ for (const key of ['destroyed', 'notFound']) {
+ if (next[key]) next[key] = next[key].map(rename);
+ }
+ return [name, next, callId];
+ }),
+ };
+}
diff --git a/lib/jmap/types.ts b/lib/jmap/types.ts
index 647a57309..6a19f659f 100644
--- a/lib/jmap/types.ts
+++ b/lib/jmap/types.ts
@@ -51,6 +51,8 @@ export interface Email {
// subject / body excerpt with the matched terms in , set on search
// hits only. See lib/search-snippet.ts.
searchSnippet?: { subject: string | null; preview: string | null };
+ /** A search row only the local store found. It's no sign of new mail, whatever its date (lib/jmap/search-merge.ts). */
+ foundLocally?: boolean;
textBody?: EmailBodyPart[];
htmlBody?: EmailBodyPart[];
bodyValues?: Record;
diff --git a/lib/launch-handoff.ts b/lib/launch-handoff.ts
new file mode 100644
index 000000000..8f5be39ec
--- /dev/null
+++ b/lib/launch-handoff.ts
@@ -0,0 +1,587 @@
+/**
+ * Files and links that arrive from outside the app, on their way to the part
+ * of the app that handles them: a .eml to the viewer, a .ics to the calendar
+ * import, a .vcf to the contacts import, shared files and links to a new
+ * draft.
+ *
+ * Three things feed it: the launchQueue consumer
+ * (components/protocol/protocol-launch-handler-provider.tsx), the service
+ * worker's share target (public/sw.js) and, later, the desktop app's bridge,
+ * because launchQueue never fires in Electron. A bridge only has to call
+ * handOffFiles, handOffDraft or handOffNewMessage.
+ *
+ * The pending mailto next to it (lib/protocol-handlers/session.ts) is JSON in
+ * sessionStorage, which can't hold a File. So a handoff lives in this module's
+ * memory, and everything except a .eml also goes into the Cache API: signing
+ * in with SSO, or after a session ended, leaves the page, and the file has to
+ * still be there afterwards.
+ *
+ * What is stored is sealed with a key of its own, and the key stays in this
+ * tab's sessionStorage, so a second window can't take it. The worker passes
+ * its key in the landing address's fragment. What is stored goes when it is
+ * taken, after HANDOFF_TTL_MS, when newer handoffs need the room, at sign-out
+ * and when offline mode wipes.
+ *
+ * Anyone can POST to the share target, or link to a landing address, so what
+ * arrives that way is untrusted: the provider asks the user before it gets
+ * here (peekStoredHandoff, then adoptStoredHandoff or discardStoredHandoff).
+ * Chromium's link capturing can bring a cross-site form POST into an installed
+ * app's window, so that goes for app windows too. Only a bridge skips it.
+ */
+
+import { stripBidiControls } from '@/lib/bidi';
+import { matchSurface } from '@/lib/deep-links';
+import { cleanMailtoBody, cleanMailtoSubject } from '@/lib/protocol-handlers/mailto';
+
+export type HandoffKind = 'compose' | 'eml' | 'calendar' | 'contacts';
+
+export interface Handoff {
+ id: string;
+ kind: HandoffKind;
+ files: File[];
+ /** New draft only. */
+ subject?: string;
+ body?: string;
+ createdAt: number;
+}
+
+/** The service worker writes this cache too, in the same layout and with the same limits. */
+export const HANDOFF_CACHE = 'bulwark-launch-handoff-v1';
+export const HANDOFF_TTL_MS = 15 * 60 * 1000;
+export const HANDOFF_MAX_ENTRIES = 5;
+export const HANDOFF_MAX_BYTES = 100 * 1024 * 1024;
+const STORE_PREFIX = '/__bulwark/handoff/';
+const TAB_KEYS_KEY = 'bulwark:launch-handoffs';
+/** A launch can arrive twice: as launchQueue's target and as the page's own address. */
+const NEW_MESSAGE_REPEAT_MS = 2000;
+
+type Listener = (kind: HandoffKind) => void;
+export type HandoffLoss = 'expired' | 'missing';
+
+const queue: Handoff[] = [];
+const stored = new Map>();
+const kindListeners = new Map>();
+const anyListeners = new Set();
+const lossListeners = new Set<(loss: HandoffLoss) => void>();
+let lastNewMessageAt = 0;
+let expiryTimer: ReturnType | null = null;
+/** Bumped by clearHandoffs: a store still under way when it ran takes itself back. */
+let clearCount = 0;
+
+function newId(): string {
+ return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+}
+
+function cacheApi(): CacheStorage | null {
+ return typeof caches !== 'undefined' && caches && typeof caches.open === 'function' ? caches : null;
+}
+
+function readTabKeys(): Record {
+ try {
+ const parsed: unknown = JSON.parse(sessionStorage.getItem(TAB_KEYS_KEY) ?? '{}');
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : {};
+ } catch {
+ return {};
+ }
+}
+
+function writeTabKeys(keys: Record): void {
+ try {
+ if (Object.keys(keys).length > 0) sessionStorage.setItem(TAB_KEYS_KEY, JSON.stringify(keys));
+ else sessionStorage.removeItem(TAB_KEYS_KEY);
+ } catch {
+ // Hardened or private modes: the handoff stays in memory only.
+ }
+}
+
+function setTabKey(id: string, key: string | null): void {
+ const keys = readTabKeys();
+ if (key) keys[id] = key;
+ else delete keys[id];
+ writeTabKeys(keys);
+}
+
+function toBase64Url(bytes: Uint8Array): string {
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function fromBase64Url(text: string): Uint8Array