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
feat: infer WhatsApp message direction from an optional your-name field (#2160)
[._.]/ Adam Eivy69a164a7c3dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0b82dc420a..468fcdef37 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,6 +47,7 @@- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.- **[issue-2151] iMessage ingestion (macOS)** — a new Settings → iMessage tab lets you pull your Mac's Messages history into the activity timeline and your Tribe touchpoints. It reads `~/Library/Messages/chat.db` read-only (never writing to Apple's database) using a built-in SQLite reader — no new dependencies — and matches conversations to the people you track by phone number (a new phone field on Tribe people, matched in E.164 form) as well as email. It's off by default and opt-in: enable it, set a sync interval, and use "Check setup" to confirm PortOS has macOS Full Disk Access (with a clear fix if it doesn't) or "Sync now" to run immediately. Only conversation metadata and a short preview line are stored — full message text stays in chat.db — and, like Tribe, nothing federates to your peers. Re-syncs are incremental and idempotent, so running it repeatedly never double-logs.+- **[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.## Privacy Centerdiff --git a/client/src/components/timeline/ActivityImportPanel.jsx b/client/src/components/timeline/ActivityImportPanel.jsxindex 582c2df38f..398af41daf 100644--- a/client/src/components/timeline/ActivityImportPanel.jsx+++ b/client/src/components/timeline/ActivityImportPanel.jsx@@ -1,4 +1,4 @@-import { useState, useRef } from 'react';+import { useState, useRef, useEffect } from 'react';import { Upload, Loader2, CheckCircle2 } from 'lucide-react';import toast from '../ui/Toast';@@ -20,8 +20,14 @@ import toast from '../ui/Toast';// also takes another single-file shape (e.g. Discord's older// `messages.csv`) widens it so the OS file picker doesn't hide// a file the server would actually accept.+// controls — optional JSX rendered under the help text for source-specific+// inputs (e.g. WhatsApp's "your name"). Given `{ disabled }` so+// the input greys out while a request is in flight.+// importOptions— optional extra options spread into every importFn call (both+// preview and import), so a control's value reaches the server.+// Changing it invalidates a stale preview so counts can't lie.const DEFAULT_ACCEPT = '.zip,.json,application/zip,application/json';-export default function ActivityImportPanel({ icon: Icon, title, noun, help, importFn, renderPreview, onImported, accept = DEFAULT_ACCEPT }) {+export default function ActivityImportPanel({ icon: Icon, title, noun, help, importFn, renderPreview, onImported, accept = DEFAULT_ACCEPT, controls, importOptions }) {const [open, setOpen] = useState(false);const [file, setFile] = useState(null);const [busy, setBusy] = useState(false);@@ -34,6 +40,16 @@ export default function ActivityImportPanel({ icon: Icon, title, noun, help, impconst reset = () => { reqIdRef.current += 1; setFile(null); setPreview(null); setResult(null); };+ // A control (e.g. WhatsApp's "your name") changing after a preview would make+ // the shown counts stale — invalidate any in-flight response and clear the+ // preview so the user re-previews with the new option before importing.+ const optionsKey = JSON.stringify(importOptions ?? null);+ useEffect(() => {+ reqIdRef.current += 1;+ setPreview(null);+ setResult(null);+ }, [optionsKey]);+const pickFile = (e) => {const next = e.target.files?.[0] || null;reqIdRef.current += 1; // invalidate any in-flight response for the old file@@ -47,7 +63,7 @@ export default function ActivityImportPanel({ icon: Icon, title, noun, help, impconst rid = ++reqIdRef.current;setBusy(true);setResult(null);- importFn(file, { preview: true, silent: true })+ importFn(file, { preview: true, silent: true, ...importOptions }).then((res) => {if (rid !== reqIdRef.current) return;setPreview(res);@@ -61,7 +77,7 @@ export default function ActivityImportPanel({ icon: Icon, title, noun, help, impif (!file || busy) return;const rid = ++reqIdRef.current;setBusy(true);- importFn(file, { preview: false, silent: true })+ importFn(file, { preview: false, silent: true, ...importOptions }).then((res) => {if (rid !== reqIdRef.current) return;setResult(res);@@ -89,6 +105,8 @@ export default function ActivityImportPanel({ icon: Icon, title, noun, help, imp<div className="flex flex-col gap-3 border-t border-port-border p-3"><p className="text-xs text-gray-500">{help}</p>+ {typeof controls === 'function' ? controls({ disabled: busy }) : controls}+<div className="flex flex-wrap items-center gap-2"><label className={`inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 ${busy ? 'cursor-not-allowed opacity-40' : 'cursor-pointer hover:border-port-accent'}`}><Upload size={14} />diff --git a/client/src/components/timeline/WhatsappImportPanel.jsx b/client/src/components/timeline/WhatsappImportPanel.jsxindex 04069aedd3..9076eba743 100644--- a/client/src/components/timeline/WhatsappImportPanel.jsx+++ b/client/src/components/timeline/WhatsappImportPanel.jsx@@ -1,13 +1,17 @@+import { useState } from 'react';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.+// Bulk-backfill importer for a WhatsApp "Export chat" transcript (#2160), built on+// the shared ActivityImportPanel seam. WhatsApp exports don't mark which sender is+// "you", so an optional "your name" field classifies direction: a sender matching+// it becomes a sent message, everyone else received. Left blank, every message is+// a neutral event (the sender is always kept per event).export default function WhatsappImportPanel({ onImported }) {+ const [yourName, setYourName] = useState('');+ const trimmed = yourName.trim();+return (<ActivityImportPanelicon={MessagesSquare}@@ -16,6 +20,7 @@ export default function WhatsappImportPanel({ onImported }) {importFn={api.importWhatsappHistory}onImported={onImported}accept=".txt,.zip,text/plain,application/zip"+ importOptions={trimmed ? { yourName: trimmed } : undefined}help={(<>In WhatsApp, open a chat → <span className="text-gray-300">⋯ More → Export chat</span> (without@@ -24,9 +29,28 @@ export default function WhatsappImportPanel({ onImported }) {imported. Re-imports are safe.</>)}+ controls={({ disabled }) => (+ <div className="flex flex-col gap-1">+ <label htmlFor="whatsapp-your-name" className="text-xs text-gray-400">+ Your name in this chat <span className="text-gray-600">(optional — marks your messages as sent)</span>+ </label>+ <input+ id="whatsapp-your-name"+ type="text"+ value={yourName}+ onChange={(e) => setYourName(e.target.value)}+ disabled={disabled}+ placeholder="e.g. how your contacts saved you"+ className="w-full max-w-xs rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-gray-200 placeholder:text-gray-600 focus:border-port-accent focus:outline-none disabled:opacity-40"+ />+ </div>+ )}renderPreview={(summary) => (<><div>{summary.messages} message(s) from {summary.uniqueSenders} sender(s)</div>+ {summary.directionKnown && (+ <div>{summary.sent} sent, {summary.received} received</div>+ )}{summary.chatTitle && <div>Chat: {summary.chatTitle}</div>}{dateRangeLabel(summary.from, summary.to) && (<div>Range: {dateRangeLabel(summary.from, summary.to)}</div>diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.jsindex bf4b369f2f..090319ffca 100644--- a/client/src/services/apiTimeline.js+++ b/client/src/services/apiTimeline.js@@ -25,10 +25,15 @@ export const getTimelineEvents = (options = {}) => {// `preview: true` returns parse-only counts + a summary without writing; a real// import is idempotent so re-imports are safe. request() detects the FormData// body and lets the browser set the boundary.-const importFile = (path, file, { preview = false, ...options } = {}) => {+const importFile = (path, file, { preview = false, fields = {}, ...options } = {}) => {const formData = new FormData();formData.append('file', file);formData.append('preview', preview ? 'true' : 'false');+ // Source-specific extra text fields (e.g. WhatsApp's `yourName`). Blank values+ // are dropped so the server sees "not provided" rather than an empty string.+ for (const [name, value] of Object.entries(fields)) {+ if (value != null && String(value).trim() !== '') formData.append(name, String(value));+ }return request(path, { method: 'POST', body: formData, ...options });};@@ -46,7 +51,9 @@ export const importTakeoutLocationHistory = (file, options = {}) =>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);+// WhatsApp "Export chat" transcript (`_chat.txt`, standalone or zipped) — each+// message becomes a timeline event (dedupe on a content hash). An optional+// `yourName` classifies direction: a sender matching it → sent, others →+// received; absent → neutral `message` events.+export const importWhatsappHistory = (file, { yourName, ...options } = {}) =>+ importFile('/timeline/import/whatsapp', file, { ...options, fields: { yourName } });diff --git a/server/routes/timeline.js b/server/routes/timeline.jsindex 6b92704c30..c2f4023c6a 100644--- a/server/routes/timeline.js+++ b/server/routes/timeline.js@@ -56,13 +56,25 @@ const uploadWhatsapp = uploadSingle('file', {// the recognized true/false tokens; any other string is left as-is so Zod// rejects it with a 400 rather than silently coercing an unknown value to a// (write-path) real import.-const importBodySchema = z.object({- preview: z.preprocess((v) => {- if (typeof v !== 'string') return v;- if (v === 'true' || v === '1') return true;- if (v === 'false' || v === '0' || v === '') return false;- return v; // unrecognized → Zod boolean check fails → 400- }, z.boolean().optional().default(false)),+const previewField = z.preprocess((v) => {+ if (typeof v !== 'string') return v;+ if (v === 'true' || v === '1') return true;+ if (v === 'false' || v === '0' || v === '') return false;+ return v; // unrecognized → Zod boolean check fails → 400+}, z.boolean().optional().default(false));++const importBodySchema = z.object({ preview: previewField });++// WhatsApp adds an optional "your name" so a sender matching it is classified as+// a sent (vs received) message. A blank multipart field means "not provided" →+// neutral events, so an empty string is coerced to undefined rather than matching+// the empty sender. Capped to keep the metadata payload bounded.+const whatsappImportBodySchema = z.object({+ preview: previewField,+ yourName: z.preprocess(+ (v) => (typeof v === 'string' && v.trim() === '' ? undefined : v),+ z.string().max(200).optional(),+ ),});const dayQuerySchema = z.object({@@ -100,12 +112,16 @@ router.get('/events', asyncHandler(async (req, res) => {// are safe. The uploaded temp file is ALWAYS unlinked, success or not, and BOTH// validation and the import run inside the cleanup chain so a rejected `preview`// value still unlinks the already-staged temp upload.-const importHandler = (importFn) => asyncHandler(async (req, res) => {+// `schema` validates the multipart text fields (defaulting to just `preview`);+// `toOptions` maps the validated body to the importer's option object so a source+// with extra fields (WhatsApp's `yourName`) threads them through the same seam.+const importHandler = (importFn, { schema = importBodySchema, toOptions } = {}) => asyncHandler(async (req, res) => {const file = req.file;if (!file?.path) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });const run = async () => {- const { preview } = validateRequest(importBodySchema, req.body);- return importFn(file, { dryRun: preview });+ const body = validateRequest(schema, req.body);+ const options = toOptions ? toOptions(body) : { dryRun: body.preview };+ return importFn(file, options);};const result = await run().finally(() => unlink(file.path).catch(() => {}));res.json(result);@@ -126,8 +142,12 @@ router.post('/import/takeout-location', uploadTakeoutLocation, importHandler(improuter.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));+// transcript (`_chat.txt`, standalone or zipped) → message events (dedupe on a+// content hash, since WhatsApp lines carry no message id). An optional `yourName`+// classifies direction (sent vs received); absent → neutral `message` events.+router.post('/import/whatsapp', uploadWhatsapp, importHandler(importWhatsappHistory, {+ schema: whatsappImportBodySchema,+ toOptions: (body) => ({ dryRun: body.preview, yourName: body.yourName ?? null }),+}));export default router;diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.jsindex e97ff39e11..9c314010b8 100644--- a/server/routes/timeline.test.js+++ b/server/routes/timeline.test.js@@ -263,7 +263,7 @@ describe('timeline import routes', () => {expect(r.body.recorded).toBe(2);expect(importWhatsappHistory).toHaveBeenCalledWith(expect.objectContaining({ originalname: 'WhatsApp Chat with Alice.txt' }),- { dryRun: false },+ { dryRun: false, yourName: null },);});@@ -277,7 +277,31 @@ describe('timeline import routes', () => {.send(body);expect(r.status).toBe(200);expect(r.body.dryRun).toBe(true);- expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true, yourName: null });+ });++ it('whatsapp threads yourName through for direction inference', async () => {+ const { boundary, body } = multipart(+ { preview: 'false', yourName: 'Alice' },+ { filename: 'WhatsApp Chat with Bob.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(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: 'Alice' });+ });++ it('whatsapp treats a blank yourName field as not provided (neutral)', async () => {+ const { boundary, body } = multipart(+ { preview: 'false', yourName: ' ' },+ { filename: 'WhatsApp Chat with Bob.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(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: null });});it('whatsapp rejects a disallowed file type with 400', async () => {diff --git a/server/services/whatsappImport.js b/server/services/whatsappImport.jsindex 584914daaa..c218d94cbc 100644--- a/server/services/whatsappImport.js+++ b/server/services/whatsappImport.js@@ -15,12 +15,17 @@* 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.)+ * Direction (sent vs received) is NOT marked in a WhatsApp export — every line+ * carries the sender's saved display name, with no flag for "you". The importer+ * therefore takes an OPTIONAL `yourName`: when supplied, a line whose sender+ * matches it (case-insensitive, trimmed) becomes a `message.sent` event and every+ * other line a `message.received` event (the same kinds the email importer uses);+ * when omitted, each message stays a neutral `message` event under source+ * `whatsapp`. The sender is always kept in `participants`/`metadata`. Direction is+ * NOT part of the dedupe key, so re-importing the same export with a `yourName`+ * this time inserts nothing over an earlier neutral import (the rows already+ * exist) — clearing the source's events and re-importing applies the new+ * classification.** 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@@ -140,10 +145,18 @@ function resolveYmd(msg, order) {// the word "omitted" ("I omitted that detail") isn't mis-flagged.const MEDIA_RE = /^\s*(<[^>]*\bomitted\b[^>]*>|(?:image|video|audio|gif|sticker|document|contact card|media)\s+omitted|<attached:[^>]*>)\s*$|<attached:/i;+// Normalize a display name for direction matching: trimmed + lower-cased, or ''+// for a non-string / empty value (never matches a real sender).+export function normalizeName(name) {+ return typeof name === 'string' ? name.trim().toLowerCase() : '';+}+// 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 } = {}) {+// offset-less local wall-clock; `chatTitle` labels the conversation. `yourName`+// (optional) classifies direction: a sender matching it → `message.sent`, others+// → `message.received`; when absent, the event stays a neutral `message`.+export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = null, timezone = null, yourName = 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')}`@@ -183,9 +196,17 @@ export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = nul.digest('hex').slice(0, 24);+ // Direction: match the sender against `yourName` (if given) to pick sent vs+ // received; a neutral `message` when no name is supplied. Deliberately NOT part+ // of the dedupe key (see the file header) so re-importing with a name over an+ // earlier neutral import is a no-op rather than a duplicate.+ const normalizedYou = normalizeName(yourName);+ const isSelf = normalizedYou !== '' && normalizeName(msg.sender) === normalizedYou;+ const kind = normalizedYou === '' ? 'message' : (isSelf ? 'message.sent' : 'message.received');+return {source: 'whatsapp',- kind: 'message',+ kind,happenedAt,title,summary: shortSummary(summaryText),@@ -196,17 +217,18 @@ export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = nulsender: msg.sender,hasMedia,dateOrder: order,+ direction: normalizedYou === '' ? null : (isSelf ? 'sent' : 'received'),},};}// 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 } = {}) {+// filter every message under it. `yourName` (optional) classifies direction.+export function whatsappActivityCandidates(messages = [], { chatTitle = null, timezone = null, yourName = null } = {}) {if (!Array.isArray(messages)) return [];const order = detectDateOrder(messages);return messages- .map((msg) => whatsappMessageToCandidate(msg, { order, chatTitle, timezone }))+ .map((msg) => whatsappMessageToCandidate(msg, { order, chatTitle, timezone, yourName })).filter(Boolean);}@@ -216,12 +238,16 @@ export function summarizeWhatsappCandidates(candidates = []) {const list = Array.isArray(candidates) ? candidates : [];let earliest = null;let latest = null;+ let sent = 0;+ let received = 0;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;}+ if (c.metadata?.direction === 'sent') sent += 1;+ else if (c.metadata?.direction === 'received') received += 1;const sender = c.metadata?.sender || c.participants?.[0]?.name;if (sender) senderCounts.set(sender, (senderCounts.get(sender) || 0) + 1);}@@ -235,6 +261,11 @@ export function summarizeWhatsappCandidates(candidates = []) {from: earliest,to: latest,topSenders,+ // sent/received are 0 when no `yourName` was supplied (all neutral); the UI+ // only shows the breakdown when a direction was actually classified.+ sent,+ received,+ directionKnown: sent > 0 || received > 0,chatTitle: list[0]?.metadata?.chatTitle || null,};}@@ -315,12 +346,12 @@ export async function readWhatsappText(file) {// 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 } = {}) {+export async function importWhatsappHistory(file, { dryRun = false, yourName = null } = {}) {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 candidates = whatsappActivityCandidates(messages, { chatTitle, timezone, yourName });const summary = summarizeWhatsappCandidates(candidates);if (dryRun) {console.log(`💬 WhatsApp import preview: ${candidates.length} message(s) from ${messages.length} line-record(s)`);diff --git a/server/services/whatsappImport.test.js b/server/services/whatsappImport.test.jsindex d2624b2de8..143177df37 100644--- a/server/services/whatsappImport.test.js+++ b/server/services/whatsappImport.test.js@@ -142,6 +142,30 @@ describe('whatsappMessageToCandidate', () => {expect(whatsappMessageToCandidate(sys, { timezone: UTC })).toBeNull();expect(whatsappMessageToCandidate(null, { timezone: UTC })).toBeNull();});++ it('stays a neutral message with no direction when no yourName is given', () => {+ const c = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC });+ expect(c.kind).toBe('message');+ expect(c.metadata.direction).toBeNull();+ });++ it('classifies a sender matching yourName as message.sent (case/space-insensitive)', () => {+ const c = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, yourName: ' alice ' });+ expect(c.kind).toBe('message.sent');+ expect(c.metadata.direction).toBe('sent');+ });++ it('classifies a non-matching sender as message.received', () => {+ const c = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, yourName: 'Bob' });+ expect(c.kind).toBe('message.received');+ expect(c.metadata.direction).toBe('received');+ });++ it('keeps the dedupe key independent of direction so re-import with a name is a no-op', () => {+ const neutral = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC });+ const sent = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, yourName: 'Alice' });+ expect(sent.dedupeKey).toBe(neutral.dedupeKey);+ });});describe('whatsappActivityCandidates', () => {@@ -152,6 +176,13 @@ describe('whatsappActivityCandidates', () => {expect(out.every((c) => c.source === 'whatsapp' && c.kind === 'message')).toBe(true);expect(out.every((c) => c.metadata.dateOrder === 'mdy')).toBe(true);});+ it('classifies direction across the batch when yourName is supplied', () => {+ const out = whatsappActivityCandidates(parseWhatsappChat(androidChat), { timezone: UTC, yourName: 'Alice' });+ const alice = out.find((c) => c.metadata.sender === 'Alice');+ const bob = out.find((c) => c.metadata.sender === 'Bob');+ expect(alice.kind).toBe('message.sent');+ expect(bob.kind).toBe('message.received');+ });it('returns [] for non-arrays', () => {expect(whatsappActivityCandidates(null)).toEqual([]);expect(whatsappActivityCandidates({})).toEqual([]);@@ -168,10 +199,18 @@ describe('summarizeWhatsappCandidates', () => {expect(s.to).toBe('2024-01-15T18:32:10.000Z');expect(s.topSenders[0]).toEqual({ name: 'Alice', count: 2 });expect(s.chatTitle).toBe('Group');+ expect(s.directionKnown).toBe(false);+ });+ it('tallies sent/received when direction is classified', () => {+ const candidates = whatsappActivityCandidates(parseWhatsappChat(iosChat), { timezone: UTC, yourName: 'Alice' });+ const s = summarizeWhatsappCandidates(candidates);+ expect(s.directionKnown).toBe(true);+ expect(s.sent).toBe(2); // Alice x2+ expect(s.received).toBe(1); // Bob x1});it('handles an empty batch', () => {const s = summarizeWhatsappCandidates([]);- expect(s).toMatchObject({ messages: 0, uniqueSenders: 0, from: null, to: null });+ expect(s).toMatchObject({ messages: 0, uniqueSenders: 0, from: null, to: null, sent: 0, received: 0, directionKnown: false });expect(s.topSenders).toEqual([]);});});