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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add WhatsApp chat-export importer to the human-activity timeline
[._.]/ Adam Eivy2d035a4d31f0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0cbb7952ee..ae9b8dbdb8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -152,6 +152,8 @@- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.+- **[issue-2160] Bulk-history importer for WhatsApp chat exports → timeline `message` events, on the shared import seam.** The `/timeline` page gains a collapsible "Import WhatsApp chat" panel alongside the Spotify, location, and Discord ones: in WhatsApp open a chat → ⋯ More → Export chat, then upload the `_chat.txt` (or the exported `.zip`) → preview parsed message counts + unique senders + chat title + date-range + top senders → confirm, and every message lands as an idempotent `message` event (source `whatsapp`) via the existing `recordEvents()` infra. Both export layouts parse: iOS bracketed lines (`[2024-01-15, 6:30:45 PM] Name: …`) and Android dash lines (`1/15/24, 6:30 PM - Name: …`), with multi-line message bodies folded back together, bidi marks stripped, system notices (encryption/group changes) skipped, and media-only lines kept with a placeholder. Because WhatsApp timestamps are LOCAL wall-clock with no offset, they're anchored to your configured timezone (reusing the calendar importer's `resolveEventInstant`) instead of the server's OS zone; the M/D vs D/M date order is auto-detected per file (a component >12 disambiguates; ambiguous files default to M/D). WhatsApp exports don't mark which sender is "you", so direction (sent vs received) is left neutral for now with the sender kept per event — a later reclassification pass, plus Gmail/YouTube/browser-history sources, stay tracked on #2160. Since WhatsApp lines carry no message id, the dedupe key is a stable content hash of (chat, instant, sender, body), so re-imports and overlapping exports never double-count. Built on the same shared seam: the generic `ActivityImportPanel`, the `importHandler` route factory, and the `importFile` client wrapper. (`server/services/whatsappImport.js`, `server/routes/timeline.js`, `server/lib/navManifest.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/WhatsappImportPanel.jsx`, `client/src/pages/Timeline.jsx`)+- **[issue-2160] Bulk-history importer for Discord data packages → `message.sent` events, on the shared import seam.** The `/timeline` page gains a collapsible "Import Discord history" panel alongside the Spotify and location ones: request your Discord "data package" (Settings → Data & Privacy → Request all of my Data), then upload the ZIP (or a single `messages.json`/`.csv`) → preview parsed message counts + unique channels + date-range + top channels → confirm, and every message you sent lands as an idempotent `message.sent` event (source `discord`) via the existing `recordEvents()` infra. Because every message in the package is authored by the account owner and Discord message IDs are globally-unique snowflakes, the dedupe key is just the message id, so re-imports and overlapping exports never double-count. Both export vintages parse: newer `messages.json` and older `messages.csv` (a small in-tree RFC-4180 CSV reader — no new deps — handles quoted fields with embedded commas/quotes/newlines), each channel's `channel.json` is joined to give guild/DM context, offset-less CSV timestamps are anchored to UTC, and attachment-only messages are kept with a placeholder body. Built on the same shared seam: the generic `ActivityImportPanel`, the `importHandler` route factory, and the `importFile` client wrapper. (`server/services/discordImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/DiscordImportPanel.jsx`, `client/src/pages/Timeline.jsx`)- **[issue-2160] Bulk-history importer for Google Takeout Location History → `place.visit` events, on the shared import seam.** The `/timeline` page gains a collapsible "Import Google location history" panel alongside the Spotify one: upload the Takeout "Location History (Timeline)" ZIP (or a single `Semantic Location History` JSON) → preview parsed visit/place counts + date-range + top places → confirm, and every place visit lands as an idempotent `place.visit` event (source `location`) via the existing `recordEvents()` infra (dedupe on place identity + visit start, so re-imports and overlapping exports never double-count). Both export vintages parse: classic server-side Timeline (`timelineObjects[].placeVisit` with E7 coords and ISO or epoch-ms durations) and the 2024+ on-device export (`semanticSegments[].visit.topCandidate` with `latLng` strings). Travel/activity segments carry no "where was I" signal and are dropped; the raw `Records.json` GPS dump is deliberately skipped. The two importers now share ONE seam: a generic `ActivityImportPanel` (pick → preview → confirm, stale-response-guarded) that Spotify + location wrap thinly, one `importHandler` route factory on `/api/timeline`, and one `importFile` client wrapper — so the remaining sources are small follow-ups. (`server/services/takeoutLocationImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/{ActivityImportPanel,TakeoutLocationImportPanel,SpotifyImportPanel}.jsx`, `client/src/pages/Timeline.jsx`)diff --git a/client/src/components/timeline/WhatsappImportPanel.jsx b/client/src/components/timeline/WhatsappImportPanel.jsxnew file mode 100644index 0000000000..04069aedd3--- /dev/null+++ b/client/src/components/timeline/WhatsappImportPanel.jsx@@ -0,0 +1,43 @@+import { MessagesSquare } from 'lucide-react';+import * as api from '../../services/api';+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';++// Bulk-backfill importer for a WhatsApp "Export chat" transcript (#2160) → every+// message becomes a neutral timeline event, built on the shared+// ActivityImportPanel seam. WhatsApp exports don't mark which sender is "you", so+// direction (sent vs received) is left neutral for now — the sender is kept per+// event for a later reclassification pass.+export default function WhatsappImportPanel({ onImported }) {+ return (+ <ActivityImportPanel+ icon={MessagesSquare}+ title="Import WhatsApp chat"+ noun="message"+ importFn={api.importWhatsappHistory}+ onImported={onImported}+ accept=".txt,.zip,text/plain,application/zip"+ help={(+ <>+ In WhatsApp, open a chat → <span className="text-gray-300">⋯ More → Export chat</span> (without+ media is smaller), then upload the <span className="font-mono">.txt</span> (or the+ exported <span className="font-mono">.zip</span>) here. Both sides of the conversation are+ imported. Re-imports are safe.+ </>+ )}+ renderPreview={(summary) => (+ <>+ <div>{summary.messages} message(s) from {summary.uniqueSenders} sender(s)</div>+ {summary.chatTitle && <div>Chat: {summary.chatTitle}</div>}+ {dateRangeLabel(summary.from, summary.to) && (+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</div>+ )}+ {summary.topSenders?.length > 0 && (+ <div className="mt-1 truncate">+ Top: {summary.topSenders.slice(0, 5).map((s) => s.name).join(', ')}+ </div>+ )}+ </>+ )}+ />+ );+}diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsxindex b1f8aeae4c..4fb4fad84b 100644--- a/client/src/pages/Timeline.jsx+++ b/client/src/pages/Timeline.jsx@@ -8,6 +8,7 @@ import PageHeader from '../components/PageHeader';import SpotifyImportPanel from '../components/timeline/SpotifyImportPanel';import TakeoutLocationImportPanel from '../components/timeline/TakeoutLocationImportPanel';import DiscordImportPanel from '../components/timeline/DiscordImportPanel';+import WhatsappImportPanel from '../components/timeline/WhatsappImportPanel';import * as api from '../services/api';import toast from '../components/ui/Toast';import { formatClockTime, formatDurationSec } from '../utils/formatters';@@ -210,6 +211,7 @@ export default function Timeline() {<SpotifyImportPanel onImported={() => setReloadKey((k) => k + 1)} /><TakeoutLocationImportPanel onImported={() => setReloadKey((k) => k + 1)} /><DiscordImportPanel onImported={() => setReloadKey((k) => k + 1)} />+ <WhatsappImportPanel onImported={() => setReloadKey((k) => k + 1)} /><Histogram histogram={histogram} />diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.jsindex 490e9ce49a..bf4b369f2f 100644--- a/client/src/services/apiTimeline.js+++ b/client/src/services/apiTimeline.js@@ -45,3 +45,8 @@ export const importTakeoutLocationHistory = (file, options = {}) =>// (dedupe on the globally-unique Discord message snowflake id).export const importDiscordHistory = (file, options = {}) =>importFile('/timeline/import/discord', file, options);++// WhatsApp "Export chat" transcript (`_chat.txt`, standalone or zipped) — every+// message becomes a neutral timeline event (dedupe on a content hash).+export const importWhatsappHistory = (file, options = {}) =>+ importFile('/timeline/import/whatsapp', file, options);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 8e4ba85c0f..7d9b381503 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -100,7 +100,7 @@ export const NAV_COMMANDS = [{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Comms', aliases: ['messages-config', 'comms-config'], keywords: ['comms'] },{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Comms', aliases: ['messages-sync', 'comms-sync'], keywords: ['comms'] },{ id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Brain', aliases: ['openclaw'] },- { id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily'] },+ { id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily', 'import', 'backfill', 'whatsapp', 'spotify', 'discord'] },{ id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },{ id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },diff --git a/server/routes/timeline.js b/server/routes/timeline.jsindex 47b21da0c8..6b92704c30 100644--- a/server/routes/timeline.js+++ b/server/routes/timeline.js@@ -9,6 +9,7 @@ import * as humanActivity from '../services/humanActivity.js';import { importSpotifyHistory } from '../services/spotifyImport.js';import { importTakeoutLocationHistory } from '../services/takeoutLocationImport.js';import { importDiscordHistory } from '../services/discordImport.js';+import { importWhatsappHistory } from '../services/whatsappImport.js';const router = Router();@@ -38,6 +39,17 @@ const uploadDiscord = uploadSingle('file', {cb(new ServerError('Only Discord data-package ZIP, JSON, or CSV files are accepted', { status: 400, code: 'BAD_REQUEST' }));},});+// WhatsApp "Export chat" ships a `_chat.txt` transcript, either standalone or+// bundled in a ZIP with media — accept the plain text file alongside the ZIP.+const uploadWhatsapp = uploadSingle('file', {+ limits: { fileSize: 200 * 1024 * 1024 },+ fileFilter: (req, file, cb) => {+ const ok = /\.(zip|txt)$/i.test(file.originalname)+ || ['application/zip', 'application/x-zip-compressed', 'text/plain'].includes(file.mimetype);+ if (ok) return cb(null, true);+ cb(new ServerError('Only WhatsApp chat-export TXT or ZIP files are accepted', { status: 400, code: 'BAD_REQUEST' }));+ },+});// `preview` (a multipart text field, so it arrives as a string) toggles a// parse-only dry run — count what would be imported without writing. Only map@@ -113,4 +125,9 @@ router.post('/import/takeout-location', uploadTakeoutLocation, importHandler(imp// (dedupe on the globally-unique Discord message snowflake id).router.post('/import/discord', uploadDiscord, importHandler(importDiscordHistory));+// POST /api/timeline/import/whatsapp — bulk-backfill a WhatsApp "Export chat"+// transcript (`_chat.txt`, standalone or zipped) → neutral message events+// (dedupe on a content hash, since WhatsApp lines carry no message id).+router.post('/import/whatsapp', uploadWhatsapp, importHandler(importWhatsappHistory));+export default router;diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.jsindex 56eaf7fd65..e97ff39e11 100644--- a/server/routes/timeline.test.js+++ b/server/routes/timeline.test.js@@ -38,6 +38,17 @@ vi.mock('../services/discordImport.js', () => ({})),}));+vi.mock('../services/whatsappImport.js', () => ({+ importWhatsappHistory: vi.fn(async (file, opts) => ({+ dryRun: Boolean(opts?.dryRun),+ parsed: 3,+ mapped: 2,+ recorded: opts?.dryRun ? 0 : 2,+ skipped: opts?.dryRun ? 0 : 0,+ summary: { messages: 2, uniqueSenders: 2, from: null, to: null, topSenders: [], chatTitle: null },+ })),+}));+vi.mock('../services/humanActivity.js', () => ({getDaySummary: vi.fn(async () => ({ date: '2026-07-07', events: [] })),listEvents: vi.fn(async () => []),@@ -46,6 +57,7 @@ vi.mock('../services/humanActivity.js', () => ({import { importSpotifyHistory } from '../services/spotifyImport.js';import { importTakeoutLocationHistory } from '../services/takeoutLocationImport.js';import { importDiscordHistory } from '../services/discordImport.js';+import { importWhatsappHistory } from '../services/whatsappImport.js';import timelineRoutes from './timeline.js';function makeApp() {@@ -238,4 +250,45 @@ describe('timeline import routes', () => {expect(r.status).toBe(400);expect(importDiscordHistory).not.toHaveBeenCalled();});++ it('POST /import/whatsapp parses a .txt upload and calls the importer', async () => {+ const { boundary, body } = multipart(+ { preview: 'false' },+ { filename: 'WhatsApp Chat with Alice.txt', contentType: 'text/plain', content: '[2024-01-15, 6:30:45 PM] Alice: hi\n' },+ );+ const r = await request(app).post('/api/timeline/import/whatsapp')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body.recorded).toBe(2);+ expect(importWhatsappHistory).toHaveBeenCalledWith(+ expect.objectContaining({ originalname: 'WhatsApp Chat with Alice.txt' }),+ { dryRun: false },+ );+ });++ it('whatsapp accepts a zipped export as a preview dry run', async () => {+ const { boundary, body } = multipart(+ { preview: 'true' },+ { filename: 'WhatsApp Chat - Alice.zip', contentType: 'application/zip', content: 'PK...' },+ );+ const r = await request(app).post('/api/timeline/import/whatsapp')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body.dryRun).toBe(true);+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });+ });++ it('whatsapp rejects a disallowed file type with 400', async () => {+ const { boundary, body } = multipart(+ {},+ { filename: 'data.json', contentType: 'application/json', content: '{}' },+ );+ const r = await request(app).post('/api/timeline/import/whatsapp')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(400);+ expect(importWhatsappHistory).not.toHaveBeenCalled();+ });});diff --git a/server/services/whatsappImport.js b/server/services/whatsappImport.jsnew file mode 100644index 0000000000..789fc385be--- /dev/null+++ b/server/services/whatsappImport.js@@ -0,0 +1,313 @@+/**+ * WhatsApp chat-export importer (#2160) — bulk historical backfill into the+ * human-activity timeline.+ *+ * WhatsApp's "Export chat" (per-conversation: chat → ⋯ → More → Export chat)+ * produces either a single `_chat.txt` / `WhatsApp Chat with <name>.txt`, or a+ * ZIP bundling that `_chat.txt` alongside any exported media. Each text line is a+ * timestamped message:+ *+ * iOS: `[2024-01-15, 6:30:45 PM] Alice: hey there`+ * Android: `1/15/24, 6:30 PM - Alice: hey there`+ *+ * A message body may span multiple lines; continuation lines carry no timestamp+ * header and are folded back into the preceding message. System notices ("…are+ * end-to-end encrypted", "Alice created group …") have no `Sender: ` segment and+ * are skipped — they aren't activity the user authored or received.+ *+ * Direction (sent vs received) is NOT recoverable from a WhatsApp export — it+ * labels every line with the sender's saved display name, with no marker for+ * "you". Rather than guess and mislabel half the events, each message maps to a+ * neutral `message` activity event under source `whatsapp`, with the sender kept+ * in `participants`/`metadata` so a later pass (given the user's own name) can+ * reclassify without re-importing. (See the #2160 follow-up.)+ *+ * Timestamps are LOCAL wall-clock with no offset — unlike the UTC Spotify/Discord+ * exports — so they're interpreted in the user's configured timezone via+ * `resolveEventInstant`, the same anchor the calendar importer uses for+ * offset-less values.+ *+ * Idempotent: WhatsApp lines carry no message id, so the dedupe key is a stable+ * content hash of (chat, instant, sender, body). Re-importing the same or an+ * overlapping export is a no-op via `recordEvents`'s `ON CONFLICT DO NOTHING`. No+ * AI-provider calls; parsing is deterministic and LLM-free.+ */+import { createReadStream } from 'fs';+import { readFile } from 'fs/promises';+import { createHash } from 'crypto';+import { parseZip, collectZipEntry } from '../lib/zipStream.js';+import { shortSummary, recordEvents, resolveEventInstant } from './humanActivity.js';+import { getUserTimezone } from '../lib/timezone.js';++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).+// ---------------------------------------------------------------------------++// Bidi marks WhatsApp (iOS especially) injects around timestamps, senders, and+// media placeholders; stripped so they can't leak into the parsed fields.+const BIDI_MARKS = /[-]/g;++// One message-line header: an optional `[`, a date (three numeric groups in some+// order), a time (12h with AM/PM or 24h), an optional `]`, and an optional+// Android ` - ` separator, then the remainder ("Sender: body" or a system line).+// The capture groups are (d1, d2, d3, hour, minute, second?, ampm?, rest).+const HEADER_RE = /^\[?\s*(\d{1,4})[.\/-](\d{1,2})[.\/-](\d{1,4}),?\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([AaPp]\.?[Mm]\.?)?\s*\]?\s*(?:[-–]\s+)?(.*)$/;++// Convert a 12h clock + AM/PM token to a 0–23 hour. A 24h line (no token) passes+// through unchanged. 12 AM → 0, 12 PM → 12.+function to24Hour(hour, ampm) {+ const h = Number(hour);+ if (!ampm) return h;+ const pm = /p/i.test(ampm);+ if (pm) return h === 12 ? 12 : h + 12; // 12 PM stays 12; 1–11 PM → +12+ return h === 12 ? 0 : h; // 12 AM → 0; 1–11 AM unchanged+}++// Split the post-timestamp remainder into { sender, body, isSystem }. A real+// message is `Sender: body`; the sender segment must be a single line with no+// embedded colon-space (display names don't contain ": "). Anything else is a+// system notice (encryption info, group membership changes, "You deleted…").+function splitSenderBody(rest) {+ const idx = rest.indexOf(': ');+ if (idx === -1) return { sender: null, body: rest, isSystem: true };+ const sender = rest.slice(0, idx).trim();+ if (!sender || sender.includes('\n')) return { sender: null, body: rest, isSystem: true };+ return { sender, body: rest.slice(idx + 2), isSystem: false };+}++// Parse a full `_chat.txt` into raw messages. Continuation lines (no header) fold+// into the previous message's body. Numeric date groups are kept UN-ordered here+// (mdy vs dmy is a per-file property resolved by detectDateOrder); the time is+// already normalized to a 24h hour.+export function parseWhatsappChat(text) {+ const messages = [];+ const lines = String(text ?? '').replace(BIDI_MARKS, '').split(/\r?\n/);+ for (const line of lines) {+ const m = HEADER_RE.exec(line);+ if (!m) {+ // Continuation of a multi-line message body.+ if (messages.length) messages[messages.length - 1].body += `\n${line}`;+ continue;+ }+ const [, d1, d2, d3, hour, minute, second, ampm, rest] = m;+ const { sender, body, isSystem } = splitSenderBody(rest);+ messages.push({+ d1: Number(d1),+ d2: Number(d2),+ d3: Number(d3),+ hour24: to24Hour(hour, ampm),+ minute: Number(minute),+ second: second ? Number(second) : 0,+ sender,+ body,+ isSystem,+ });+ }+ return messages;+}++// Infer the file's date component order from the parsed messages. WhatsApp writes+// the phone's locale format, so the whole file shares one order. A 4-digit first+// group is unambiguously year-first; otherwise a first group >12 forces D/M and a+// second group >12 forces M/D. Ambiguous files (all components ≤12) default to+// M/D/Y — the US/iOS default — which is the safest single guess.+export function detectDateOrder(messages = []) {+ const list = Array.isArray(messages) ? messages : [];+ for (const m of list) if (m.d1 >= 1000) return 'ymd';+ for (const m of list) if (m.d1 > 12) return 'dmy';+ for (const m of list) if (m.d2 > 12) return 'mdy';+ return 'mdy';+}++// Resolve a message's numeric date groups to a { year, month, day } under the+// given order, normalizing a 2-digit year to 20xx (WhatsApp postdates 2009).+function resolveYmd(msg, order) {+ let year;+ let month;+ let day;+ if (order === 'ymd') { [year, month, day] = [msg.d1, msg.d2, msg.d3]; }+ else if (order === 'dmy') { [day, month, year] = [msg.d1, msg.d2, msg.d3]; }+ else { [month, day, year] = [msg.d1, msg.d2, msg.d3]; }+ if (year < 100) year += 2000;+ return { year, month, day };+}++// A body that's only a media placeholder ("<Media omitted>", "image omitted",+// "<attached: …>") still carries autobiographical signal (you sent/received+// something then) — flagged so the summary can show a placeholder rather than an+// empty line.+const MEDIA_RE = /(<media omitted>|omitted>?$|<attached:|\bomitted\b)/i;++// Map ONE raw WhatsApp message to an activity candidate, or null if it's a system+// notice, lacks a sender, or has an unresolvable timestamp. `timezone` anchors the+// offset-less local wall-clock; `chatTitle` labels the conversation.+export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = null, timezone = null } = {}) {+ if (!msg || msg.isSystem || !msg.sender) return null;+ const { year, month, day } = resolveYmd(msg, order);+ const iso = `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`+ + `T${String(msg.hour24).padStart(2, '0')}:${String(msg.minute).padStart(2, '0')}:${String(msg.second).padStart(2, '0')}`;+ const instant = resolveEventInstant(iso, timezone);+ if (!instant) return null;+ const happenedAt = instant.toISOString();++ const bodyText = String(msg.body ?? '').trim();+ const hasMedia = MEDIA_RE.test(bodyText);+ const title = chatTitle ? `WhatsApp: ${chatTitle}` : 'WhatsApp message';+ const summaryText = bodyText || (hasMedia ? '(media)' : '');++ // No message id in the export — hash the identifying tuple so re-imports of the+ // same (or an overlapping) export collapse deterministically. Two identical+ // bodies from the same sender at the same second in the same chat are+ // indistinguishable in the file, so collapsing them is correct.+ const dedupeKey = createHash('sha1')+ .update(`${chatTitle || ''} ${happenedAt} ${msg.sender} ${bodyText}`)+ .digest('hex')+ .slice(0, 24);++ return {+ source: 'whatsapp',+ kind: 'message',+ happenedAt,+ title,+ summary: shortSummary(summaryText),+ participants: [{ name: msg.sender }],+ dedupeKey: `whatsapp:${dedupeKey}`,+ metadata: {+ chatTitle: chatTitle || null,+ sender: msg.sender,+ hasMedia,+ dateOrder: order,+ },+ };+}++// Map a full parsed chat to candidates: detect the date order once, then map ++// filter every message under it.+export function whatsappActivityCandidates(messages = [], { chatTitle = null, timezone = null } = {}) {+ if (!Array.isArray(messages)) return [];+ const order = detectDateOrder(messages);+ return messages+ .map((msg) => whatsappMessageToCandidate(msg, { order, chatTitle, timezone }))+ .filter(Boolean);+}++// Summarize a candidate batch for the import preview: message count, unique+// senders, date range, and the most-active senders. Pure over candidates.+export function summarizeWhatsappCandidates(candidates = []) {+ const list = Array.isArray(candidates) ? candidates : [];+ let earliest = null;+ let latest = null;+ const senderCounts = new Map();+ for (const c of list) {+ if (c.happenedAt) {+ if (!earliest || c.happenedAt < earliest) earliest = c.happenedAt;+ if (!latest || c.happenedAt > latest) latest = c.happenedAt;+ }+ const sender = c.metadata?.sender || c.participants?.[0]?.name;+ if (sender) senderCounts.set(sender, (senderCounts.get(sender) || 0) + 1);+ }+ const topSenders = [...senderCounts.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ .map(([name, count]) => ({ name, count }));+ return {+ messages: list.length,+ uniqueSenders: senderCounts.size,+ from: earliest,+ to: latest,+ topSenders,+ chatTitle: list[0]?.metadata?.chatTitle || null,+ };+}++// Derive a human chat title from the uploaded file name. WhatsApp names direct+// exports `WhatsApp Chat with Alice.txt` / `WhatsApp Chat - Alice.zip`; the+// in-ZIP text is always the anonymous `_chat.txt` (→ no title). Returns null when+// nothing meaningful can be extracted.+export function deriveChatTitle(fileName) {+ if (!fileName) return null;+ const base = String(fileName).replace(/\.[^.]+$/, '').trim();+ if (!base || /^_chat$/i.test(base)) return null;+ const m = /^whatsapp chat(?:\s+with|\s*[-–])?\s*(.+)$/i.exec(base);+ const title = (m ? m[1] : base).trim();+ return title || null;+}++// ---------------------------------------------------------------------------+// File ingestion (single `.txt` or an "Export chat" ZIP) → chat text.+// ---------------------------------------------------------------------------++const isZip = (file) =>+ file?.mimetype === 'application/zip' ||+ file?.mimetype === 'application/x-zip-compressed' ||+ /\.zip$/i.test(file?.originalname || '');++// The chat transcript inside an "Export chat" ZIP is `_chat.txt`; older/renamed+// exports may name it `WhatsApp Chat with X.txt`. Prefer `_chat.txt`, else the+// first `.txt` member.+const isChatTxtEntry = (entryPath) => /(?:^|\/)_chat\.txt$/i.test(String(entryPath || ''));+const isAnyTxtEntry = (entryPath) => /\.txt$/i.test(String(entryPath || ''));++// Extract the chat transcript text from an "Export chat" ZIP. Media entries are+// drained and ignored. Resolves to the transcript string ('' if none found).+async function readTextFromZip(filePath) {+ let preferred = null; // _chat.txt+ let fallback = null; // first other .txt+ const reads = [];+ await new Promise((resolve, reject) => {+ let settled = false;+ const src = createReadStream(filePath);+ const parser = parseZip();+ const settle = (fn) => (...args) => {+ if (settled) return;+ settled = true;+ // On failure tear down the pipeline so a large upload with an early error+ // doesn't keep reading to EOF.+ if (fn === reject) { src.destroy(); parser.destroy?.(); }+ fn(...args);+ };+ src.on('error', settle(reject));+ src+ .pipe(parser)+ .on('entry', (entry) => {+ if (isChatTxtEntry(entry.path)) {+ reads.push(collectZipEntry(entry).then((buf) => { preferred = buf.toString('utf-8'); }).catch(settle(reject)));+ } else if (isAnyTxtEntry(entry.path) && fallback === null) {+ reads.push(collectZipEntry(entry).then((buf) => { if (fallback === null) fallback = buf.toString('utf-8'); }).catch(settle(reject)));+ } else {+ entry.autodrain();+ }+ })+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))+ .on('error', settle(reject));+ });+ return preferred ?? fallback ?? '';+}++// Read the chat transcript text from an uploaded file (a single `.txt` or an+// "Export chat" ZIP).+export async function readWhatsappText(file) {+ if (!file?.path) return '';+ if (isZip(file)) return readTextFromZip(file.path);+ return readFile(file.path, 'utf-8');+}++// End-to-end import seam: read the file → parse → map → (preview | record).+// Returns counts + a preview summary. `dryRun` parses and summarizes WITHOUT+// writing so the UI can show what will be imported before committing. Because+// `recordEvents` is idempotent, committing (or re-committing) is always safe.+export async function importWhatsappHistory(file, { dryRun = false } = {}) {+ const text = await readWhatsappText(file);+ const messages = parseWhatsappChat(text);+ const timezone = await getUserTimezone();+ const chatTitle = deriveChatTitle(file?.originalname);+ const candidates = whatsappActivityCandidates(messages, { chatTitle, timezone });+ const summary = summarizeWhatsappCandidates(candidates);+ if (dryRun) {+ console.log(`💬 WhatsApp import preview: ${candidates.length} message(s) from ${messages.length} line-record(s)`);+ return { dryRun: true, parsed: messages.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };+ }+ const { recorded, skipped } = await recordEvents(candidates);+ console.log(`💬 WhatsApp import: ${recorded} new message(s) recorded, ${skipped} duplicate/invalid (from ${messages.length} line-record(s))`);+ return { dryRun: false, parsed: messages.length, mapped: candidates.length, recorded, skipped, summary };+}diff --git a/server/services/whatsappImport.test.js b/server/services/whatsappImport.test.jsnew file mode 100644index 0000000000..2306de1911--- /dev/null+++ b/server/services/whatsappImport.test.js@@ -0,0 +1,176 @@+import { describe, it, expect } from 'vitest';+import {+ parseWhatsappChat,+ detectDateOrder,+ whatsappMessageToCandidate,+ whatsappActivityCandidates,+ summarizeWhatsappCandidates,+ deriveChatTitle,+} from './whatsappImport.js';++// A UTC timezone keeps the offset-less-local → instant resolution deterministic+// in the assertions below (WhatsApp timestamps carry no offset).+const UTC = 'UTC';++// Representative iOS-style export (bracketed, 12h clock, seconds).+const iosChat = [+ '[2024-01-15, 6:30:45 PM] Alice: hey there',+ '[2024-01-15, 6:31:00 PM] Bob: hi! how are you?',+ 'this is a second line of the same message',+ '[2024-01-15, 6:32:10 PM] Alice: <attached: 00000042-PHOTO-2024-01-15.jpg>',+].join('\n');++// Representative Android-style export (dash separator, no brackets/seconds).+const androidChat = [+ '1/15/24, 6:30 PM - Messages to this chat are now end-to-end encrypted.',+ '1/15/24, 6:30 PM - Alice: morning',+ '1/15/24, 6:45 PM - Bob: <Media omitted>',+].join('\n');++describe('parseWhatsappChat', () => {+ it('parses iOS bracketed lines with a 12h clock and seconds', () => {+ const msgs = parseWhatsappChat(iosChat);+ expect(msgs).toHaveLength(3);+ expect(msgs[0]).toMatchObject({ sender: 'Alice', body: 'hey there', hour24: 18, minute: 30, second: 45, isSystem: false });+ });++ it('folds continuation lines into the preceding message body', () => {+ const msgs = parseWhatsappChat(iosChat);+ expect(msgs[1].sender).toBe('Bob');+ expect(msgs[1].body).toBe('hi! how are you?\nthis is a second line of the same message');+ });++ it('strips bidi marks from media placeholders', () => {+ const msgs = parseWhatsappChat(iosChat);+ expect(msgs[2].body).toBe('<attached: 00000042-PHOTO-2024-01-15.jpg>');+ });++ it('parses Android dash-separated lines and flags system notices', () => {+ const msgs = parseWhatsappChat(androidChat);+ expect(msgs).toHaveLength(3);+ expect(msgs[0]).toMatchObject({ isSystem: true, sender: null });+ expect(msgs[1]).toMatchObject({ sender: 'Alice', body: 'morning', hour24: 18, minute: 30 });+ expect(msgs[2]).toMatchObject({ sender: 'Bob', body: '<Media omitted>' });+ });++ it('converts 12 AM/PM edge hours correctly', () => {+ const msgs = parseWhatsappChat([+ '[2024-01-15, 12:00:00 AM] A: midnight',+ '[2024-01-15, 12:00:00 PM] A: noon',+ ].join('\n'));+ expect(msgs[0].hour24).toBe(0);+ expect(msgs[1].hour24).toBe(12);+ });++ it('returns [] for empty input', () => {+ expect(parseWhatsappChat('')).toEqual([]);+ });+});++describe('detectDateOrder', () => {+ it('detects year-first from a 4-digit leading group', () => {+ expect(detectDateOrder(parseWhatsappChat('[2024-01-15, 6:30:00 PM] A: x'))).toBe('ymd');+ });+ it('detects day-first when a first group exceeds 12', () => {+ expect(detectDateOrder(parseWhatsappChat('15/01/24, 6:30 PM - A: x'))).toBe('dmy');+ });+ it('detects month-first when a second group exceeds 12', () => {+ expect(detectDateOrder(parseWhatsappChat('1/15/24, 6:30 PM - A: x'))).toBe('mdy');+ });+ it('defaults to month-first when fully ambiguous', () => {+ expect(detectDateOrder(parseWhatsappChat('1/2/24, 6:30 PM - A: x'))).toBe('mdy');+ });+});++describe('whatsappMessageToCandidate', () => {+ const [msg] = parseWhatsappChat('[2024-01-15, 6:30:45 PM] Alice: hey there');++ it('maps a message to a neutral message activity candidate in the given tz', () => {+ const c = whatsappMessageToCandidate(msg, { order: 'ymd', chatTitle: 'Alice', timezone: UTC });+ expect(c).toMatchObject({+ source: 'whatsapp',+ kind: 'message',+ happenedAt: '2024-01-15T18:30:45.000Z',+ title: 'WhatsApp: Alice',+ });+ expect(c.summary).toBe('hey there');+ expect(c.participants).toEqual([{ name: 'Alice' }]);+ expect(c.metadata).toMatchObject({ chatTitle: 'Alice', sender: 'Alice', hasMedia: false, dateOrder: 'ymd' });+ });++ it('interprets the offset-less local time in the user timezone', () => {+ const c = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: 'America/New_York' });+ // 6:30:45 PM EST (UTC-5) → 23:30:45 UTC.+ expect(c.happenedAt).toBe('2024-01-15T23:30:45.000Z');+ });++ it('builds a stable dedupe key that changes with content', () => {+ const c1 = whatsappMessageToCandidate(msg, { order: 'ymd', chatTitle: 'Alice', timezone: UTC });+ const c2 = whatsappMessageToCandidate(msg, { order: 'ymd', chatTitle: 'Alice', timezone: UTC });+ expect(c1.dedupeKey).toBe(c2.dedupeKey);+ expect(c1.dedupeKey).toMatch(/^whatsapp:[0-9a-f]{24}$/);+ const [other] = parseWhatsappChat('[2024-01-15, 6:30:45 PM] Alice: different body');+ expect(whatsappMessageToCandidate(other, { order: 'ymd', chatTitle: 'Alice', timezone: UTC }).dedupeKey)+ .not.toBe(c1.dedupeKey);+ });++ it('flags a media-only body and shows a placeholder summary', () => {+ const [media] = parseWhatsappChat('[2024-01-15, 6:30:45 PM] Bob: <Media omitted>');+ const c = whatsappMessageToCandidate(media, { order: 'ymd', timezone: UTC });+ expect(c.metadata.hasMedia).toBe(true);+ expect(c.summary).toBe('<Media omitted>');+ });++ it('drops system notices and messages with no sender', () => {+ const [sys] = parseWhatsappChat('1/15/24, 6:30 PM - Messages are end-to-end encrypted.');+ expect(whatsappMessageToCandidate(sys, { timezone: UTC })).toBeNull();+ expect(whatsappMessageToCandidate(null, { timezone: UTC })).toBeNull();+ });+});++describe('whatsappActivityCandidates', () => {+ it('detects the order once and maps every non-system message', () => {+ const out = whatsappActivityCandidates(parseWhatsappChat(androidChat), { chatTitle: 'Alice', timezone: UTC });+ // 3 lines: 1 system (dropped) + 2 real messages.+ expect(out).toHaveLength(2);+ expect(out.every((c) => c.source === 'whatsapp' && c.kind === 'message')).toBe(true);+ expect(out.every((c) => c.metadata.dateOrder === 'mdy')).toBe(true);+ });+ it('returns [] for non-arrays', () => {+ expect(whatsappActivityCandidates(null)).toEqual([]);+ expect(whatsappActivityCandidates({})).toEqual([]);+ });+});++describe('summarizeWhatsappCandidates', () => {+ it('computes range, message count, unique senders, and top senders', () => {+ const candidates = whatsappActivityCandidates(parseWhatsappChat(iosChat), { chatTitle: 'Group', timezone: UTC });+ const s = summarizeWhatsappCandidates(candidates);+ expect(s.messages).toBe(3);+ expect(s.uniqueSenders).toBe(2);+ expect(s.from).toBe('2024-01-15T18:30:45.000Z');+ expect(s.to).toBe('2024-01-15T18:32:10.000Z');+ expect(s.topSenders[0]).toEqual({ name: 'Alice', count: 2 });+ expect(s.chatTitle).toBe('Group');+ });+ it('handles an empty batch', () => {+ const s = summarizeWhatsappCandidates([]);+ expect(s).toMatchObject({ messages: 0, uniqueSenders: 0, from: null, to: null });+ expect(s.topSenders).toEqual([]);+ });+});++describe('deriveChatTitle', () => {+ it('extracts the contact/group name from a WhatsApp export filename', () => {+ expect(deriveChatTitle('WhatsApp Chat with Alice.txt')).toBe('Alice');+ expect(deriveChatTitle('WhatsApp Chat - Book Club.zip')).toBe('Book Club');+ });+ it('returns null for the anonymous in-zip _chat.txt', () => {+ expect(deriveChatTitle('_chat.txt')).toBeNull();+ expect(deriveChatTitle('')).toBeNull();+ expect(deriveChatTitle(null)).toBeNull();+ });+ it('falls back to the bare basename when no known prefix matches', () => {+ expect(deriveChatTitle('my-export.txt')).toBe('my-export');+ });+});