Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2160]): Gmail full-history .mbox backfill importer

Adam Eivy5ae547f99aed
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 03d3420647..b6db444cb4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -74,6 +74,7 @@
- **[issue-2160] WhatsApp import direction inference** — the WhatsApp chat backfill importer now takes an optional "your name in this chat" field. When set, messages from a sender matching that name land as `message.sent` events and everyone else as `message.received` (the same kinds email uses); left blank, messages stay neutral `message` events as before. The preview shows the sent/received split before you commit. Direction isn't part of the dedupe key, so an earlier neutral import isn't double-counted — clear the source's events and re-import to apply the classification.
- **[issue-2160] WhatsApp import optional chat label — hardens the cross-chat dedupe collision** — the WhatsApp chat backfill importer now takes an optional "chat label" field. WhatsApp exports carry no stable chat id (the filename differs between a `WhatsApp Chat - Alice.zip` and the bare `_chat.txt` extracted from it), so the content-hash dedupe key was deliberately un-scoped — which meant two DIFFERENT chats that each contained a same-named sender sending an identical message at the same timestamp granularity could collapse into a single event. Supplying a chat label (e.g. "Family group") now folds that stable, user-supplied scope into the dedupe hash so distinct chats key apart, and the label also becomes the displayed chat title. Left blank, the dedupe key is byte-identical to before, so existing imports and their idempotency are unchanged; use the same label consistently for a given chat across re-imports. (`server/services/whatsappImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/WhatsappImportPanel.jsx`)
- **[issue-2153] YouTube watch history** — YouTube killed its watch-history API, so PortOS ingests your viewing two complementary ways, both landing as `media.watch` events on the activity timeline (taste signal for the digital twin). A new **Settings → YouTube** tab scrapes your signed-in `youtube.com/feed/history` page through the managed browser — off by default and opt-in: log into YouTube in the managed browser, run "Check setup" to confirm you're signed in, set a conservative scrape interval (the history page only shows day-bucketed entries, so a few times a day is plenty), and use "Scrape now" to run immediately. Selector failures degrade to a surfaced sync-status error instead of crashing, and all the page selectors live in one place for easy repair. For reliable historical data (and a fallback whenever the scrape breaks), the **Timeline** page gains a **Google Takeout backfill** importer: upload your "YouTube and YouTube Music → history" export (the ZIP or a single `watch-history.json`) and every watch is imported with its exact timestamp. Both paths share a per-video-per-local-day dedupe key, so a Takeout backfill and the live scrape reconcile without double-counting, and re-imports/re-scrapes are always safe. Like the rest of the timeline, watches are machine-local and never federate to your peers. (`server/services/youtubeSync.js`, `server/services/youtubeImport.js`, `server/services/youtubeScheduler.js`, `server/routes/youtube.js`, `client/src/components/settings/YoutubeTab.jsx`, `client/src/components/timeline/YoutubeImportPanel.jsx`)
+- **[issue-2160] Gmail full-history backfill** — the **Timeline** page gains a Gmail importer that backfills your entire email history from a Google Takeout "Mail" export into the activity timeline as sent/received message events. Because a Gmail `.mbox` is routinely several gigabytes and won't fit the upload flow the other backfills use, this importer reads it from a local path instead: extract your Takeout Mail export on the machine, then point it at the `.mbox` file (or the whole extracted `Mail/` folder) and it streams the file in place — a multi-gigabyte mailbox never has to be uploaded or held in memory. Only header metadata is read (subject, sender, recipients, date, thread) — never message bodies — matching the timeline's privacy stance. Each message is deduplicated by its email Message-ID, so re-importing the same export (or a newer overlapping one) never double-counts; Preview streams and counts the messages (with a sent/received split, date range, and top correspondents) before you commit. Direction comes from Gmail's own "Sent" label, and an optional "your email" field refines it. Like the rest of the timeline, these events are machine-local and never federate to your peers. (`server/services/gmailMboxImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/GmailMboxImportPanel.jsx`, `client/src/pages/Timeline.jsx`)
## Privacy Center
diff --git a/client/src/components/timeline/GmailMboxImportPanel.jsx b/client/src/components/timeline/GmailMboxImportPanel.jsx
new file mode 100644
index 0000000000..9edc61351e
--- /dev/null
+++ b/client/src/components/timeline/GmailMboxImportPanel.jsx
@@ -0,0 +1,164 @@
+import { useState, useRef } from 'react';
+import { Mail, Loader2, CheckCircle2 } from 'lucide-react';
+import * as api from '../../services/api';
+import toast from '../ui/Toast';
+import { dateRangeLabel } from './ActivityImportPanel';
+
+// Bulk-backfill importer for a Google Takeout Gmail `.mbox` (#2160) →
+// message.sent/message.received events. Unlike the other timeline importers this
+// is PATH-BASED, not an upload: a Gmail mbox is routinely multiple GB and doesn't
+// fit the 200MB upload flow, so the user names a local file/folder the server
+// streams. Same two-step flow (preview → import) and idempotent server-side, so
+// re-importing the same export never double-counts. Collapsed by default.
+export default function GmailMboxImportPanel({ onImported }) {
+ const [open, setOpen] = useState(false);
+ const [mboxPath, setMboxPath] = useState('');
+ const [yourEmail, setYourEmail] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [preview, setPreview] = useState(null);
+ const [result, setResult] = useState(null);
+ // Monotonic request id — a response only applies if it's still the latest, so
+ // editing the path mid-flight can't let a stale response land.
+ const reqIdRef = useRef(0);
+
+ const invalidate = () => { reqIdRef.current += 1; setPreview(null); setResult(null); };
+ const onPathChange = (v) => { setMboxPath(v); invalidate(); };
+ const onEmailChange = (v) => { setYourEmail(v); invalidate(); };
+ const reset = () => { reqIdRef.current += 1; setPreview(null); setResult(null); };
+
+ const canRun = mboxPath.trim() && !busy;
+
+ const run = (dryRun) => {
+ if (!canRun) return;
+ const rid = ++reqIdRef.current;
+ setBusy(true);
+ if (dryRun) setResult(null);
+ api.importGmailMbox({ path: mboxPath.trim(), preview: dryRun, yourEmail: yourEmail.trim(), silent: true })
+ .then((res) => {
+ if (rid !== reqIdRef.current) return;
+ if (dryRun) {
+ setPreview(res);
+ if (!res.mapped) toast.error('No messages found at that path.');
+ } else {
+ setResult(res);
+ toast.success(`Imported ${res.recorded} message(s) (${res.skipped} already present).`);
+ if (res.recorded > 0) onImported?.();
+ }
+ })
+ .catch((err) => { if (rid === reqIdRef.current) toast.error(`${dryRun ? 'Preview' : 'Import'} failed: ${err.message}`); })
+ .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
+ };
+
+ return (
+ <div className="rounded border border-port-border bg-port-card">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-sm text-gray-300 hover:text-gray-100"
+ aria-expanded={open}
+ >
+ <Mail size={16} className="text-port-accent" />
+ <span className="font-medium">Import Gmail history</span>
+ <span className="ml-auto text-xs text-gray-500">{open ? 'Hide' : 'Backfill'}</span>
+ </button>
+
+ {open && (
+ <div className="flex flex-col gap-3 border-t border-port-border p-3">
+ <p className="text-xs text-gray-500">
+ Request <span className="text-gray-300">Mail</span> from Google Takeout
+ (takeout.google.com) and extract it on this machine. Because a Gmail
+ <span className="font-mono"> .mbox</span> is often several GB, this reads it
+ from a local <span className="text-gray-300">path</span> instead of an upload —
+ point it at the <span className="font-mono">.mbox</span> file (or the extracted
+ <span className="font-mono"> Takeout/Mail/</span> folder). Only headers are read
+ (subject, sender, recipients, date) — never message bodies. Re-imports are safe.
+ </p>
+
+ <div className="flex flex-col gap-2">
+ <label htmlFor="gmail-mbox-path" className="text-xs font-medium text-gray-400">
+ Path to .mbox file or Mail folder
+ </label>
+ <input
+ id="gmail-mbox-path"
+ type="text"
+ value={mboxPath}
+ onChange={(e) => onPathChange(e.target.value)}
+ disabled={busy}
+ placeholder="~/Downloads/Takeout/Mail/All mail Including Spam and Trash.mbox"
+ className="rounded border border-port-border bg-port-bg px-2 py-1.5 font-mono text-xs text-gray-100 disabled:opacity-40"
+ />
+ <label htmlFor="gmail-mbox-email" className="mt-1 text-xs font-medium text-gray-400">
+ Your email <span className="font-normal text-gray-500">(optional — refines sent vs received)</span>
+ </label>
+ <input
+ id="gmail-mbox-email"
+ type="email"
+ value={yourEmail}
+ onChange={(e) => onEmailChange(e.target.value)}
+ disabled={busy}
+ placeholder="[email protected]"
+ className="rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-gray-100 disabled:opacity-40"
+ />
+ </div>
+
+ {!result && (
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => run(true)}
+ disabled={!canRun}
+ className="inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm hover:border-port-accent disabled:opacity-40"
+ >
+ {busy && !preview ? <Loader2 size={14} className="animate-spin" /> : null}
+ Preview
+ </button>
+ {preview && preview.mapped > 0 && (
+ <button
+ type="button"
+ onClick={() => run(false)}
+ disabled={busy}
+ className="inline-flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-sm font-medium text-white hover:opacity-90 disabled:opacity-40"
+ >
+ {busy && preview ? <Loader2 size={14} className="animate-spin" /> : null}
+ Import {preview.mapped} message{preview.mapped === 1 ? '' : 's'}
+ </button>
+ )}
+ </div>
+ )}
+
+ {preview && !result && (
+ <div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">
+ <div className="mb-1 font-medium text-gray-300">Preview</div>
+ <div>{preview.summary.messages} message(s): {preview.summary.sent} sent, {preview.summary.received} received</div>
+ <div>{preview.summary.uniqueCorrespondents} unique correspondent(s)</div>
+ {dateRangeLabel(preview.summary.from, preview.summary.to) && (
+ <div>Range: {dateRangeLabel(preview.summary.from, preview.summary.to)}</div>
+ )}
+ {preview.summary.topCorrespondents?.length > 0 && (
+ <div className="mt-1 truncate">
+ Top: {preview.summary.topCorrespondents.slice(0, 5).map((c) => c.email).join(', ')}
+ </div>
+ )}
+ </div>
+ )}
+
+ {result && (
+ <div className="rounded border border-port-success/40 bg-port-bg p-3 text-xs text-gray-300">
+ <div className="mb-1 flex items-center gap-2 font-medium text-port-success">
+ <CheckCircle2 size={14} /> Import complete
+ </div>
+ <div>{result.recorded} new message(s) recorded, {result.skipped} already present.</div>
+ <button
+ type="button"
+ onClick={reset}
+ className="mt-2 rounded border border-port-border px-2 py-1 text-gray-300 hover:border-port-accent"
+ >
+ Import another
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsx
index 4d61bd93ec..415548c9cf 100644
--- a/client/src/pages/Timeline.jsx
+++ b/client/src/pages/Timeline.jsx
@@ -11,6 +11,7 @@ import DiscordImportPanel from '../components/timeline/DiscordImportPanel';
import WhatsappImportPanel from '../components/timeline/WhatsappImportPanel';
import BrowserHistoryImportPanel from '../components/timeline/BrowserHistoryImportPanel';
import YoutubeImportPanel from '../components/timeline/YoutubeImportPanel';
+import GmailMboxImportPanel from '../components/timeline/GmailMboxImportPanel';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
import { formatClockTime, formatDurationSec } from '../utils/formatters';
@@ -213,6 +214,7 @@ export default function Timeline() {
<div className="text-sm text-gray-400">{dayLabel}</div>
</div>
+ <GmailMboxImportPanel onImported={() => setReloadKey((k) => k + 1)} />
<SpotifyImportPanel onImported={() => setReloadKey((k) => k + 1)} />
<TakeoutLocationImportPanel onImported={() => setReloadKey((k) => k + 1)} />
<DiscordImportPanel onImported={() => setReloadKey((k) => k + 1)} />
diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.js
index 099783e291..cd3f64e03b 100644
--- a/client/src/services/apiTimeline.js
+++ b/client/src/services/apiTimeline.js
@@ -70,3 +70,21 @@ export const importBrowserHistory = (file, options = {}) =>
// live scrape so the backfill and scrape reconcile).
export const importYoutubeHistory = (file, options = {}) =>
importFile('/timeline/import/youtube', file, options);
+
+// Gmail full-history metadata (#2160). Google Takeout Gmail ships a multi-GB
+// `.mbox` that doesn't fit the 200MB upload flow, so this importer is PATH-BASED:
+// the server streams a local `.mbox` file (or the extracted `Takeout/Mail/` folder)
+// the user names. Only header metadata + a short summary are stored — never the
+// message body. Each message → a `message.sent`/`message.received` event under
+// source `gmail` (dedupe on the RFC-822 Message-ID). `preview: true` streams +
+// counts without writing; an optional `yourEmail` refines sent/received direction.
+export const importGmailMbox = ({ path, preview = false, yourEmail, ...options } = {}) =>
+ request('/timeline/import/gmail', {
+ method: 'POST',
+ body: JSON.stringify({
+ path,
+ preview,
+ ...(yourEmail && String(yourEmail).trim() ? { yourEmail } : {}),
+ }),
+ ...options,
+ });
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
index c92efd1935..32387195d5 100644
--- a/server/routes/timeline.js
+++ b/server/routes/timeline.js
@@ -12,6 +12,7 @@ import { importDiscordHistory } from '../services/discordImport.js';
import { importWhatsappHistory } from '../services/whatsappImport.js';
import { importBrowserHistory } from '../services/browserHistoryImport.js';
import { importYoutubeHistory } from '../services/youtubeImport.js';
+import { importGmailMbox } from '../services/gmailMboxImport.js';
const router = Router();
@@ -175,4 +176,30 @@ router.post('/import/browser', uploadBrowserHistory, importHandler(importBrowser
// source `youtube` (dedupe on video id + local day, shared with the live scrape).
router.post('/import/youtube', uploadYoutube, importHandler(importYoutubeHistory));
+// POST /api/timeline/import/gmail — bulk-backfill Gmail full-history metadata from
+// a Google Takeout `.mbox`. Unlike the other importers this is PATH-BASED (a JSON
+// body, not a multipart upload): the Gmail mbox is routinely multiple GB and does
+// not fit the 200MB upload flow, so the server streams a local file/folder the
+// user names. Header metadata only (never the body) → message.sent/message.received
+// events under source `gmail` (dedupe on the RFC-822 Message-ID). `preview=true`
+// streams + counts without writing. `yourEmail` (optional, blank → ignored) refines
+// sent/received direction when the export's Gmail labels are absent.
+const gmailImportSchema = z.object({
+ path: z.string().trim().min(1).max(4096),
+ preview: z.boolean().optional().default(false),
+ yourEmail: z.preprocess(
+ (v) => (typeof v === 'string' && v.trim() === '' ? undefined : v),
+ z.string().max(320).optional(),
+ ),
+});
+router.post('/import/gmail', asyncHandler(async (req, res) => {
+ const { path: mboxPath, preview, yourEmail } = validateRequest(gmailImportSchema, req.body);
+ const result = await importGmailMbox({
+ path: mboxPath,
+ dryRun: preview,
+ selfEmails: yourEmail ? [yourEmail] : [],
+ });
+ res.json(result);
+}));
+
export default router;
diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.js
index 4f91ded5e8..13cd4560e8 100644
--- a/server/routes/timeline.test.js
+++ b/server/routes/timeline.test.js
@@ -60,6 +60,17 @@ vi.mock('../services/browserHistoryImport.js', () => ({
})),
}));
+vi.mock('../services/gmailMboxImport.js', () => ({
+ importGmailMbox: vi.fn(async (opts) => ({
+ dryRun: Boolean(opts?.dryRun),
+ parsed: 6,
+ mapped: 5,
+ recorded: opts?.dryRun ? 0 : 5,
+ skipped: opts?.dryRun ? 0 : 0,
+ summary: { messages: 5, sent: 2, received: 3, from: null, to: null, uniqueCorrespondents: 3, topCorrespondents: [] },
+ })),
+}));
+
vi.mock('../services/humanActivity.js', () => ({
getDaySummary: vi.fn(async () => ({ date: '2026-07-07', events: [] })),
listEvents: vi.fn(async () => []),
@@ -70,6 +81,7 @@ import { importTakeoutLocationHistory } from '../services/takeoutLocationImport.
import { importDiscordHistory } from '../services/discordImport.js';
import { importWhatsappHistory } from '../services/whatsappImport.js';
import { importBrowserHistory } from '../services/browserHistoryImport.js';
+import { importGmailMbox } from '../services/gmailMboxImport.js';
import timelineRoutes from './timeline.js';
function makeApp() {
@@ -387,4 +399,48 @@ describe('timeline import routes', () => {
expect(r.status).toBe(400);
expect(importBrowserHistory).not.toHaveBeenCalled();
});
+
+ // Gmail is PATH-BASED (a JSON body, not a multipart upload) because the Takeout
+ // `.mbox` is multi-GB and doesn't fit the 200MB upload flow.
+ it('POST /import/gmail parses a path body and calls the importer (real import)', async () => {
+ const r = await request(app).post('/api/timeline/import/gmail')
+ .send({ path: '~/Takeout/Mail/all.mbox', preview: false });
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({ recorded: 5, mapped: 5 });
+ expect(importGmailMbox).toHaveBeenCalledWith({
+ path: '~/Takeout/Mail/all.mbox', dryRun: false, selfEmails: [],
+ });
+ });
+
+ it('gmail honors preview=true as a dry run', async () => {
+ const r = await request(app).post('/api/timeline/import/gmail')
+ .send({ path: '/data/Mail', preview: true });
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({ dryRun: true, recorded: 0 });
+ expect(importGmailMbox).toHaveBeenCalledWith({ path: '/data/Mail', dryRun: true, selfEmails: [] });
+ });
+
+ it('gmail threads yourEmail through as selfEmails for direction inference', async () => {
+ const r = await request(app).post('/api/timeline/import/gmail')
+ .send({ path: '/data/all.mbox', preview: false, yourEmail: '[email protected]' });
+ expect(r.status).toBe(200);
+ expect(importGmailMbox).toHaveBeenCalledWith({
+ path: '/data/all.mbox', dryRun: false, selfEmails: ['[email protected]'],
+ });
+ });
+
+ it('gmail treats a blank yourEmail as not provided', async () => {
+ const r = await request(app).post('/api/timeline/import/gmail')
+ .send({ path: '/data/all.mbox', preview: false, yourEmail: ' ' });
+ expect(r.status).toBe(200);
+ expect(importGmailMbox).toHaveBeenCalledWith({
+ path: '/data/all.mbox', dryRun: false, selfEmails: [],
+ });
+ });
+
+ it('gmail 400s when path is missing', async () => {
+ const r = await request(app).post('/api/timeline/import/gmail').send({ preview: false });
+ expect(r.status).toBe(400);
+ expect(importGmailMbox).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/gmailMboxImport.js b/server/services/gmailMboxImport.js
new file mode 100644
index 0000000000..91a00a3591
--- /dev/null
+++ b/server/services/gmailMboxImport.js
@@ -0,0 +1,408 @@
+/**
+ * Gmail full-history metadata importer (#2160) — bulk historical backfill into
+ * the machine-local human-activity timeline (#2150).
+ *
+ * Gmail has no metadata API for the full account lifetime, but Google Takeout
+ * ships the entire mailbox as an RFC-822 **mbox** file ("Mail" product export →
+ * e.g. `Takeout/Mail/All mail Including Spam and Trash.mbox`). That file is
+ * routinely MULTIPLE GIGABYTES — it does NOT fit the 200MB multipart upload the
+ * other timeline importers use. So this importer is **path-based**: the user
+ * points it at a local `.mbox` file (or the extracted `Takeout/Mail/` folder) the
+ * server can already see on disk, and we STREAM it line-by-line so a 10GB mailbox
+ * never has to be held in memory.
+ *
+ * Privacy contract (per the design doc): we parse HEADERS ONLY and store metadata
+ * + a short summary line — never the message body. Each message maps to a
+ * `message.sent` / `message.received` activity event under source `gmail`.
+ * Direction comes from Gmail Takeout's `X-Gmail-Labels` header (which carries the
+ * `Sent` label on outbound mail); an optional `yourEmail` refines it when the
+ * From address matches.
+ *
+ * Idempotent: the dedupe key is the RFC-822 `Message-ID` (globally unique and
+ * stable), so re-importing the same export — or a newer overlapping one — is a
+ * no-op via `recordEvents`'s `ON CONFLICT DO NOTHING`. Messages missing a
+ * Message-ID (rare — some drafts) fall back to a content hash of
+ * (instant + from + subject). No AI-provider calls; parsing is deterministic and
+ * LLM-free.
+ */
+import { createReadStream } from 'fs';
+import { stat, readdir } from 'fs/promises';
+import { createInterface } from 'readline';
+import { createHash } from 'crypto';
+import { homedir } from 'os';
+import path from 'path';
+
+import { ServerError } from '../lib/errorHandler.js';
+import { shortSummary, recordEvents } from './humanActivity.js';
+
+// ---------------------------------------------------------------------------
+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).
+// ---------------------------------------------------------------------------
+
+// Map an RFC-2047 charset token to a Node Buffer encoding. Node only ships a
+// handful of built-in encodings; per the dependency policy we do NOT pull an
+// iconv library for the long tail. utf-8 and latin1 cover the overwhelming
+// majority of real mail headers, and latin1 preserves bytes (rather than
+// throwing) for windows-125x / iso-8859-x variants, so a header still round-trips
+// legibly for Western text instead of failing the whole import.
+function bufferEncodingFor(charset) {
+ const cs = String(charset || '').trim().toLowerCase();
+ if (cs === 'utf-8' || cs === 'utf8') return 'utf8';
+ if (cs === 'utf-16' || cs === 'utf-16le' || cs === 'utf16le' || cs === 'ucs-2') return 'utf16le';
+ // us-ascii / iso-8859-* / windows-125x and unknowns → latin1 (byte-preserving).
+ return 'latin1';
+}
+
+// Decode RFC-2047 "encoded-word" runs (`=?charset?B?…?=` / `=?charset?Q?…?=`)
+// found in Subject and display-name headers back to a plain string. Adjacent
+// encoded words separated only by whitespace have that whitespace removed (per
+// the spec), so a multi-part subject reassembles without stray spaces. Non-encoded
+// text passes through unchanged.
+export function decodeMimeWords(input) {
+ if (input === null || input === undefined) return '';
+ let s = String(input);
+ // Collapse the whitespace *between* two adjacent encoded words.
+ s = s.replace(/\?=\s+=\?/g, '?==?');
+ return s.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (_, charset, enc, text) => {
+ const encoding = bufferEncodingFor(charset);
+ if (enc.toUpperCase() === 'B') {
+ return Buffer.from(text, 'base64').toString(encoding);
+ }
+ // Q-encoding: `_` is a space, `=XX` is a hex byte, everything else literal.
+ const bytes = [];
+ for (let i = 0; i < text.length; i += 1) {
+ const ch = text[i];
+ if (ch === '_') {
+ bytes.push(0x20);
+ } else if (ch === '=' && i + 2 < text.length) {
+ const code = parseInt(text.slice(i + 1, i + 3), 16);
+ if (Number.isNaN(code)) { bytes.push(ch.charCodeAt(0)); continue; }
+ bytes.push(code);
+ i += 2;
+ } else {
+ bytes.push(ch.charCodeAt(0));
+ }
+ }
+ return Buffer.from(bytes).toString(encoding);
+ });
+}
+
+// Split an address-list header value on top-level commas — a comma inside a
+// quoted display name (`"Doe, John" <j@x>`) or inside angle brackets is NOT a
+// separator.
+function splitAddressList(value) {
+ const out = [];
+ let buf = '';
+ let inQuote = false;
+ let angle = 0;
+ for (const ch of String(value)) {
+ if (ch === '"') { inQuote = !inQuote; buf += ch; continue; }
+ if (!inQuote && ch === '<') { angle += 1; buf += ch; continue; }
+ if (!inQuote && ch === '>') { angle = Math.max(0, angle - 1); buf += ch; continue; }
+ if (ch === ',' && !inQuote && angle === 0) { out.push(buf); buf = ''; continue; }
+ buf += ch;
+ }
+ if (buf.trim()) out.push(buf);
+ return out;
+}
+
+// Parse one address token into { name?, email } (email lowercased), or null if
+// no usable email is present. Handles `Name <email>`, `"Quoted, Name" <email>`,
+// and a bare `email`.
+function parseOneAddress(token) {
+ const t = String(token).trim();
+ if (!t) return null;
+ const angle = /<([^>]*)>/.exec(t);
+ let email = '';
+ let name = '';
+ if (angle) {
+ email = angle[1].trim();
+ name = t.slice(0, angle.index).trim();
+ } else if (t.includes('@')) {
+ email = t;
+ }
+ email = email.replace(/^["']|["']$/g, '').trim().toLowerCase();
+ if (!email || !email.includes('@')) return null;
+ name = decodeMimeWords(name).replace(/^["']|["']$/g, '').trim();
+ return name ? { name, email } : { email };
+}
+
+// Parse an address-list header value (From / To / Cc) into [{ name?, email }].
+export function parseAddressList(value) {
+ if (!value) return [];
+ return splitAddressList(value).map(parseOneAddress).filter(Boolean);
+}
+
+// Parse a raw header block (array of lines, no leading mbox `From ` postmark)
+// into ordered [{ name, value }] entries. RFC-822 folding: a line starting with
+// whitespace continues the previous header.
+export function parseHeaderLines(headerLines) {
+ const headers = [];
+ let current = null;
+ for (const line of headerLines || []) {
+ if (/^[ \t]/.test(line) && current) {
+ current.value += ` ${line.trim()}`;
+ } else {
+ const idx = line.indexOf(':');
+ if (idx === -1) continue;
+ current = { name: line.slice(0, idx).trim().toLowerCase(), value: line.slice(idx + 1).trim() };
+ headers.push(current);
+ }
+ }
+ return headers;
+}
+
+// First value for a header name (case-insensitive), or '' if absent.
+export function headerValue(headers, name) {
+ const n = String(name).toLowerCase();
+ const h = (headers || []).find((x) => x.name === n);
+ return h ? h.value : '';
+}
+
+// Split Gmail's `X-Gmail-Labels` comma-separated label list into trimmed labels.
+export function parseGmailLabels(value) {
+ if (!value) return [];
+ return String(value).split(',').map((l) => l.trim()).filter(Boolean);
+}
+
+// Resolve an RFC-2822 `Date` header to a UTC ISO string, or null if unparseable.
+// V8's Date parses RFC-2822 dates (`Mon, 15 Jan 2024 18:30:45 -0800`) with their
+// explicit offset, so no OS-timezone ambiguity to correct for.
+export function resolveMboxInstant(value) {
+ if (!value) return null;
+ const d = new Date(String(value).trim());
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+// Strip the surrounding angle brackets from a `Message-ID` header.
+export function cleanMessageId(value) {
+ return String(value || '').replace(/[<>]/g, '').trim();
+}
+
+// Classify a message as 'sent' or 'received'. Gmail Takeout stamps outbound mail
+// with the `Sent` label in `X-Gmail-Labels`; an explicit `selfEmails` match on
+// the From address is authoritative when provided (covers exports where the
+// label is missing). Everything else is 'received'.
+export function gmailDirection(labels, fromEmail, selfEmails = []) {
+ const selfSet = new Set((selfEmails || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean));
+ if (fromEmail && selfSet.has(fromEmail)) return 'sent';
+ const hasSent = (labels || []).some((l) => String(l).trim().toLowerCase() === 'sent');
+ return hasSent ? 'sent' : 'received';
+}
+
+// Map ONE parsed message (its header lines) to a `message.sent`/`message.received`
+// activity candidate, or null when it lacks a usable Date (a false split on a body
+// line that starts with "From " has no real headers, so it drops out here). Only
+// header metadata + a short recipient/sender summary are kept — never the body.
+export function mboxMessageToCandidate(headerLines, { selfEmails = [] } = {}) {
+ const headers = parseHeaderLines(headerLines);
+ const happenedAt = resolveMboxInstant(headerValue(headers, 'date'));
+ if (!happenedAt) return null;
+
+ const messageId = cleanMessageId(headerValue(headers, 'message-id'));
+ const subject = decodeMimeWords(headerValue(headers, 'subject')).trim();
+ const fromList = parseAddressList(headerValue(headers, 'from'));
+ const toList = parseAddressList(headerValue(headers, 'to'));
+ const ccList = parseAddressList(headerValue(headers, 'cc'));
+ const labels = parseGmailLabels(headerValue(headers, 'x-gmail-labels'));
+ const threadId = headerValue(headers, 'x-gm-thrid') || null;
+
+ const fromEmail = fromList[0]?.email || '';
+ const direction = gmailDirection(labels, fromEmail, selfEmails);
+
+ const selfSet = new Set((selfEmails || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean));
+ const participants = [...fromList, ...toList, ...ccList].filter((p) => p.email && !selfSet.has(p.email));
+
+ // A message with no Message-ID (rare — some drafts) has no stable id, so hash a
+ // content identity that is stable across re-imports of the same export.
+ const dedupeKey = messageId
+ ? `gmail:${messageId}`
+ : `gmail:h:${createHash('sha1').update(`${happenedAt}|${fromEmail}|${subject}`).digest('hex').slice(0, 24)}`;
+
+ const summary = direction === 'sent'
+ ? (toList.length ? `To: ${toList.map((p) => p.name || p.email).slice(0, 3).join(', ')}` : '')
+ : (fromList.length ? `From: ${fromList[0].name || fromList[0].email}` : '');
+
+ return {
+ source: 'gmail',
+ kind: direction === 'sent' ? 'message.sent' : 'message.received',
+ happenedAt,
+ title: subject || '(no subject)',
+ summary: shortSummary(summary),
+ participants,
+ dedupeKey,
+ metadata: {
+ messageId: messageId || null,
+ threadId,
+ labels,
+ direction,
+ },
+ };
+}
+
+// Stateful mbox line reader. Feed lines one at a time via `push(line)`; `onMessage`
+// fires with the header-line array of each complete message, and `end()` flushes
+// the final message at EOF. A message boundary is a line beginning with `From `
+// (the postmark — distinct from the `From:` header, which has a colon) that
+// follows a blank line (or the start of file); the blank-line guard suppresses the
+// common false positive of a body line that happens to start with "From ".
+export function createMboxLineReader(onMessage) {
+ let headerLines = [];
+ let collecting = false;
+ let have = false;
+ let prevBlank = true;
+ return {
+ push(line) {
+ if (prevBlank && line.startsWith('From ')) {
+ if (have) onMessage(headerLines);
+ headerLines = [];
+ collecting = true;
+ have = true;
+ prevBlank = false;
+ return;
+ }
+ if (collecting) {
+ if (line === '') { collecting = false; prevBlank = true; } else { headerLines.push(line); prevBlank = false; }
+ } else {
+ prevBlank = (line === '');
+ }
+ },
+ end() {
+ if (!have) return;
+ const lines = headerLines;
+ headerLines = [];
+ have = false;
+ onMessage(lines);
+ },
+ };
+}
+
+// Parse a whole mbox TEXT string into activity candidates (pure — for tests and
+// small in-memory inputs; the real importer streams a file instead of buffering).
+export function parseMboxText(text, opts = {}) {
+ const out = [];
+ const reader = createMboxLineReader((headerLines) => {
+ const cand = mboxMessageToCandidate(headerLines, opts);
+ if (cand) out.push(cand);
+ });
+ for (const line of String(text).split(/\r?\n/)) reader.push(line);
+ reader.end();
+ return out;
+}
+
+// Fold a candidate into the running preview summary accumulator.
+function accumulateSummary(acc, cand) {
+ if (cand.happenedAt) {
+ if (!acc.from || cand.happenedAt < acc.from) acc.from = cand.happenedAt;
+ if (!acc.to || cand.happenedAt > acc.to) acc.to = cand.happenedAt;
+ }
+ if (cand.kind === 'message.sent') acc.sent += 1; else acc.received += 1;
+ for (const p of cand.participants || []) {
+ if (p.email) acc.correspondents.set(p.email, (acc.correspondents.get(p.email) || 0) + 1);
+ }
+}
+
+function newSummaryAcc() {
+ return { from: null, to: null, sent: 0, received: 0, correspondents: new Map() };
+}
+
+// Finalize the accumulator into the preview summary payload the panel renders.
+function finalizeSummary(acc) {
+ const topCorrespondents = [...acc.correspondents.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 10)
+ .map(([email, count]) => ({ email, count }));
+ return {
+ messages: acc.sent + acc.received,
+ sent: acc.sent,
+ received: acc.received,
+ from: acc.from,
+ to: acc.to,
+ uniqueCorrespondents: acc.correspondents.size,
+ topCorrespondents,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Filesystem resolution + streaming ingestion.
+// ---------------------------------------------------------------------------
+
+function expandHome(p) {
+ const s = String(p || '').trim();
+ if (s === '~') return homedir();
+ if (s.startsWith('~/')) return path.join(homedir(), s.slice(2));
+ return s;
+}
+
+// Resolve the user-supplied path to a concrete list of mbox files. A directory
+// (e.g. the extracted `Takeout/Mail/` folder) contributes every `*.mbox` inside
+// it; a single file is taken as-is (Gmail's export is one big `.mbox`, but we
+// don't force the extension so a renamed file still works).
+export async function resolveMboxFiles(inputPath) {
+ const resolved = path.resolve(expandHome(inputPath));
+ const st = await stat(resolved).catch(() => null);
+ if (!st) throw new ServerError(`No file or folder found at ${resolved}`, { status: 400, code: 'BAD_REQUEST' });
+ if (st.isDirectory()) {
+ const entries = await readdir(resolved);
+ const mboxes = entries.filter((e) => /\.mbox$/i.test(e)).sort().map((e) => path.join(resolved, e));
+ if (mboxes.length === 0) {
+ throw new ServerError(`No .mbox files found in ${resolved}`, { status: 400, code: 'BAD_REQUEST' });
+ }
+ return mboxes;
+ }
+ return [resolved];
+}
+
+// Stream one mbox file, mapping each message to a candidate. `dryRun` counts +
+// summarizes without writing; otherwise candidates flush to `recordEvents` in
+// bounded batches so a multi-GB mailbox never accumulates every candidate in
+// memory. `for await` on the readline interface applies natural backpressure while
+// a batch is being written, and propagates a read error out to the caller.
+const FLUSH_BATCH = 1000;
+async function streamMboxFile(filePath, { dryRun, selfEmails, agg }) {
+ let batch = [];
+ const reader = createMboxLineReader((headerLines) => {
+ agg.parsed += 1;
+ const cand = mboxMessageToCandidate(headerLines, { selfEmails });
+ if (!cand) return;
+ agg.mapped += 1;
+ accumulateSummary(agg.summary, cand);
+ if (!dryRun) batch.push(cand);
+ });
+
+ const rl = createInterface({ input: createReadStream(filePath, { encoding: 'utf-8' }), crlfDelay: Infinity });
+ for await (const line of rl) {
+ reader.push(line);
+ if (!dryRun && batch.length >= FLUSH_BATCH) {
+ agg.recorded += (await recordEvents(batch)).recorded;
+ batch = [];
+ }
+ }
+ reader.end();
+ if (!dryRun && batch.length > 0) {
+ agg.recorded += (await recordEvents(batch)).recorded;
+ }
+}
+
+// End-to-end path-based import seam: resolve the mbox file(s) → stream → map →
+// (preview | record). Returns counts + a preview summary. `dryRun` streams and
+// summarizes WITHOUT writing so the UI can show what will land before committing.
+// Because `recordEvents` is idempotent, committing (or re-committing) is safe.
+export async function importGmailMbox({ path: inputPath, dryRun = false, selfEmails = [] } = {}) {
+ const files = await resolveMboxFiles(inputPath);
+ const self = (selfEmails || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean);
+ const agg = { parsed: 0, mapped: 0, recorded: 0, summary: newSummaryAcc() };
+
+ for (const file of files) {
+ await streamMboxFile(file, { dryRun, selfEmails: self, agg });
+ }
+
+ const summary = finalizeSummary(agg.summary);
+ if (dryRun) {
+ console.log(`📧 Gmail mbox import preview: ${agg.mapped} message(s) from ${agg.parsed} parsed across ${files.length} file(s)`);
+ return { dryRun: true, parsed: agg.parsed, mapped: agg.mapped, recorded: 0, skipped: 0, summary };
+ }
+ const skipped = agg.mapped - agg.recorded;
+ console.log(`📧 Gmail mbox import: ${agg.recorded} new message(s) recorded, ${skipped} duplicate/invalid (from ${agg.parsed} parsed across ${files.length} file(s))`);
+ return { dryRun: false, parsed: agg.parsed, mapped: agg.mapped, recorded: agg.recorded, skipped, summary };
+}
diff --git a/server/services/gmailMboxImport.test.js b/server/services/gmailMboxImport.test.js
new file mode 100644
index 0000000000..120677f124
--- /dev/null
+++ b/server/services/gmailMboxImport.test.js
@@ -0,0 +1,241 @@
+import { describe, it, expect } from 'vitest';
+import {
+ decodeMimeWords,
+ parseAddressList,
+ parseHeaderLines,
+ headerValue,
+ parseGmailLabels,
+ resolveMboxInstant,
+ cleanMessageId,
+ gmailDirection,
+ mboxMessageToCandidate,
+ createMboxLineReader,
+ parseMboxText,
+} from './gmailMboxImport.js';
+
+describe('gmailMboxImport — pure helpers', () => {
+ describe('decodeMimeWords', () => {
+ it('passes plain text through unchanged', () => {
+ expect(decodeMimeWords('Hello world')).toBe('Hello world');
+ });
+ it('decodes a base64 (B) UTF-8 encoded word', () => {
+ // "Héllo" as UTF-8 base64
+ const enc = `=?UTF-8?B?${Buffer.from('Héllo', 'utf-8').toString('base64')}?=`;
+ expect(decodeMimeWords(enc)).toBe('Héllo');
+ });
+ it('decodes a quoted-printable (Q) encoded word with _ as space', () => {
+ expect(decodeMimeWords('=?UTF-8?Q?Hi_there=21?=')).toBe('Hi there!');
+ });
+ it('joins adjacent encoded words without the separating whitespace', () => {
+ const a = `=?UTF-8?B?${Buffer.from('foo', 'utf-8').toString('base64')}?=`;
+ const b = `=?UTF-8?B?${Buffer.from('bar', 'utf-8').toString('base64')}?=`;
+ expect(decodeMimeWords(`${a} ${b}`)).toBe('foobar');
+ });
+ it('returns empty string for null/undefined', () => {
+ expect(decodeMimeWords(null)).toBe('');
+ expect(decodeMimeWords(undefined)).toBe('');
+ });
+ });
+
+ describe('parseAddressList', () => {
+ it('parses name + angle-bracket email', () => {
+ expect(parseAddressList('Jane Doe <[email protected]>')).toEqual([
+ { name: 'Jane Doe', email: '[email protected]' },
+ ]);
+ });
+ it('keeps a comma inside a quoted display name intact', () => {
+ expect(parseAddressList('"Doe, John" <[email protected]>, [email protected]')).toEqual([
+ { name: 'Doe, John', email: '[email protected]' },
+ { email: '[email protected]' },
+ ]);
+ });
+ it('lowercases the email and decodes an encoded display name', () => {
+ const enc = `=?UTF-8?B?${Buffer.from('Björk', 'utf-8').toString('base64')}?=`;
+ expect(parseAddressList(`${enc} <[email protected]>`)).toEqual([
+ { name: 'Björk', email: '[email protected]' },
+ ]);
+ });
+ it('drops tokens with no usable email', () => {
+ expect(parseAddressList('Just A Name, [email protected]')).toEqual([{ email: '[email protected]' }]);
+ });
+ it('returns [] for empty input', () => {
+ expect(parseAddressList('')).toEqual([]);
+ });
+ });
+
+ describe('parseHeaderLines + headerValue', () => {
+ it('unfolds a folded header continuation line', () => {
+ const headers = parseHeaderLines(['Subject: hello', ' world', 'From: [email protected]']);
+ expect(headerValue(headers, 'subject')).toBe('hello world');
+ expect(headerValue(headers, 'From')).toBe('[email protected]');
+ });
+ it('is case-insensitive and returns the first occurrence', () => {
+ const headers = parseHeaderLines(['Received: one', 'Received: two']);
+ expect(headerValue(headers, 'received')).toBe('one');
+ });
+ it('returns empty string for an absent header', () => {
+ expect(headerValue(parseHeaderLines(['X: y']), 'z')).toBe('');
+ });
+ });
+
+ describe('parseGmailLabels', () => {
+ it('splits and trims a comma-separated label list', () => {
+ expect(parseGmailLabels('Inbox, Important, Category Personal')).toEqual([
+ 'Inbox', 'Important', 'Category Personal',
+ ]);
+ });
+ it('returns [] for empty input', () => {
+ expect(parseGmailLabels('')).toEqual([]);
+ });
+ });
+
+ describe('resolveMboxInstant', () => {
+ it('parses an RFC-2822 date with explicit offset', () => {
+ expect(resolveMboxInstant('Mon, 15 Jan 2024 18:30:45 -0800')).toBe('2024-01-16T02:30:45.000Z');
+ });
+ it('returns null for an unparseable date', () => {
+ expect(resolveMboxInstant('not a date')).toBeNull();
+ expect(resolveMboxInstant('')).toBeNull();
+ });
+ });
+
+ describe('cleanMessageId', () => {
+ it('strips surrounding angle brackets', () => {
+ expect(cleanMessageId('<[email protected]>')).toBe('[email protected]');
+ });
+ });
+
+ describe('gmailDirection', () => {
+ it('is sent when the Gmail labels include Sent', () => {
+ expect(gmailDirection(['Inbox', 'Sent'], '[email protected]', [])).toBe('sent');
+ });
+ it('is sent when the From matches a self email even without the label', () => {
+ expect(gmailDirection(['Inbox'], '[email protected]', ['[email protected]'])).toBe('sent');
+ });
+ it('defaults to received', () => {
+ expect(gmailDirection(['Inbox'], '[email protected]', ['[email protected]'])).toBe('received');
+ });
+ });
+});
+
+describe('gmailMboxImport — mboxMessageToCandidate', () => {
+ const headerLines = [
+ 'Message-ID: <[email protected]>',
+ 'Date: Mon, 15 Jan 2024 18:30:45 -0800',
+ 'Subject: Weekend plans',
+ 'From: Alice <[email protected]>',
+ 'X-Gmail-Labels: Inbox,Important',
+ 'X-GM-THRID: 99887766',
+ ];
+
+ it('maps a received message with metadata + no body', () => {
+ const c = mboxMessageToCandidate(headerLines, { selfEmails: ['[email protected]'] });
+ expect(c).toMatchObject({
+ source: 'gmail',
+ kind: 'message.received',
+ happenedAt: '2024-01-16T02:30:45.000Z',
+ title: 'Weekend plans',
+ dedupeKey: 'gmail:[email protected]',
+ });
+ expect(c.metadata).toMatchObject({ messageId: '[email protected]', threadId: '99887766', direction: 'received' });
+ expect(c.metadata.labels).toEqual(['Inbox', 'Important']);
+ });
+
+ it('excludes the self email from participants', () => {
+ const c = mboxMessageToCandidate(headerLines, { selfEmails: ['[email protected]'] });
+ const emails = c.participants.map((p) => p.email);
+ expect(emails).toContain('[email protected]');
+ expect(emails).toContain('[email protected]');
+ expect(emails).not.toContain('[email protected]');
+ });
+
+ it('classifies a Sent-labeled message as message.sent', () => {
+ const sent = [
+ 'Message-ID: <[email protected]>',
+ 'Date: Tue, 16 Jan 2024 09:00:00 +0000',
+ 'Subject: Re: Weekend plans',
+ 'From: Me <[email protected]>',
+ 'To: Alice <[email protected]>',
+ 'X-Gmail-Labels: Sent',
+ ];
+ const c = mboxMessageToCandidate(sent, { selfEmails: [] });
+ expect(c.kind).toBe('message.sent');
+ expect(c.summary).toBe('To: Alice');
+ });
+
+ it('falls back to a content hash when Message-ID is absent', () => {
+ const noId = headerLines.filter((l) => !l.startsWith('Message-ID'));
+ const c = mboxMessageToCandidate(noId, { selfEmails: [] });
+ expect(c.dedupeKey).toMatch(/^gmail:h:[0-9a-f]{24}$/);
+ expect(c.metadata.messageId).toBeNull();
+ });
+
+ it('returns null when the Date header is missing/unparseable', () => {
+ const noDate = ['From: [email protected]', 'Subject: hi'];
+ expect(mboxMessageToCandidate(noDate, {})).toBeNull();
+ });
+
+ it('uses (no subject) when the Subject is empty', () => {
+ const noSubject = ['Date: Mon, 15 Jan 2024 18:30:45 -0800', 'From: [email protected]'];
+ expect(mboxMessageToCandidate(noSubject, {}).title).toBe('(no subject)');
+ });
+});
+
+describe('gmailMboxImport — mbox stream state machine', () => {
+ const MBOX = [
+ 'From 1234567890@xxx Mon Jan 15 18:30:45 2024',
+ 'Message-ID: <[email protected]>',
+ 'Date: Mon, 15 Jan 2024 18:30:45 -0800',
+ 'Subject: First',
+ 'From: Alice <[email protected]>',
+ 'X-Gmail-Labels: Inbox',
+ '',
+ 'Body line one.',
+ 'From here it looks like a header but is body text.', // false "From " inside a body — must NOT split (no preceding blank)
+ '',
+ 'From 9999@yyy Tue Jan 16 09:00:00 2024',
+ 'Message-ID: <[email protected]>',
+ 'Date: Tue, 16 Jan 2024 09:00:00 +0000',
+ 'Subject: Second',
+ 'To: Bob <[email protected]>',
+ 'X-Gmail-Labels: Sent',
+ '',
+ 'Reply body.',
+ '',
+ ].join('\n');
+
+ it('parses two messages and does not split on a body line starting with "From "', () => {
+ const candidates = parseMboxText(MBOX, { selfEmails: ['[email protected]'] });
+ expect(candidates).toHaveLength(2);
+ expect(candidates[0].dedupeKey).toBe('gmail:[email protected]');
+ expect(candidates[0].kind).toBe('message.received');
+ expect(candidates[1].dedupeKey).toBe('gmail:[email protected]');
+ expect(candidates[1].kind).toBe('message.sent');
+ });
+
+ it('createMboxLineReader flushes the final message on end()', () => {
+ const seen = [];
+ const reader = createMboxLineReader((h) => seen.push(h));
+ ['From x', 'Subject: only', 'From: [email protected]'].forEach((l) => reader.push(l));
+ expect(seen).toHaveLength(0); // not yet flushed
+ reader.end();
+ expect(seen).toHaveLength(1);
+ expect(seen[0]).toEqual(['Subject: only', 'From: [email protected]']);
+ });
+
+ it('splits a "From " line only after a blank line (mbox postmark rule)', () => {
+ // A "From " line immediately after a non-blank body line is NOT a boundary.
+ const text = [
+ 'From a Mon Jan 15 00:00:00 2024',
+ 'Date: Mon, 15 Jan 2024 00:00:00 +0000',
+ '',
+ 'body',
+ 'From b Tue Jan 16 00:00:00 2024', // preceded by non-blank "body" → NOT a split
+ ].join('\n');
+ expect(parseMboxText(text, {})).toHaveLength(1);
+ });
+});