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: optional WhatsApp chat label scopes dedupe key (#2160)

Adam Eivy1279151e4fed
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 879683214c..42d44cafa1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -56,6 +56,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.
+- **[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`)
## Privacy Center
diff --git a/client/src/components/timeline/WhatsappImportPanel.jsx b/client/src/components/timeline/WhatsappImportPanel.jsx
index 9076eba743..261b555234 100644
--- a/client/src/components/timeline/WhatsappImportPanel.jsx
+++ b/client/src/components/timeline/WhatsappImportPanel.jsx
@@ -7,10 +7,18 @@ import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';
// 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).
+// a neutral event (the sender is always kept per event). An optional "chat label"
+// scopes the dedupe key to a stable chat name so two different chats that share a
+// same-named sender + identical message never collapse into one event; left blank,
+// the legacy un-scoped key is used unchanged.
export default function WhatsappImportPanel({ onImported }) {
const [yourName, setYourName] = useState('');
- const trimmed = yourName.trim();
+ const [chatLabel, setChatLabel] = useState('');
+ const trimmedName = yourName.trim();
+ const trimmedLabel = chatLabel.trim();
+ const importOptions = (trimmedName || trimmedLabel)
+ ? { ...(trimmedName ? { yourName: trimmedName } : {}), ...(trimmedLabel ? { chatLabel: trimmedLabel } : {}) }
+ : undefined;
return (
<ActivityImportPanel
@@ -20,7 +28,7 @@ export default function WhatsappImportPanel({ onImported }) {
importFn={api.importWhatsappHistory}
onImported={onImported}
accept=".txt,.zip,text/plain,application/zip"
- importOptions={trimmed ? { yourName: trimmed } : undefined}
+ importOptions={importOptions}
help={(
<>
In WhatsApp, open a chat → <span className="text-gray-300">⋯ More → Export chat</span> (without
@@ -30,19 +38,35 @@ export default function WhatsappImportPanel({ onImported }) {
</>
)}
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 className="flex flex-col gap-3">
+ <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>
+ <div className="flex flex-col gap-1">
+ <label htmlFor="whatsapp-chat-label" className="text-xs text-gray-400">
+ Chat label <span className="text-gray-600">(optional — keeps distinct chats from merging; use the same label each time)</span>
+ </label>
+ <input
+ id="whatsapp-chat-label"
+ type="text"
+ value={chatLabel}
+ onChange={(e) => setChatLabel(e.target.value)}
+ disabled={disabled}
+ placeholder="e.g. Family group"
+ 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>
</div>
)}
renderPreview={(summary) => (
diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.js
index e329452104..3cf846cb5b 100644
--- a/client/src/services/apiTimeline.js
+++ b/client/src/services/apiTimeline.js
@@ -54,9 +54,10 @@ export const importDiscordHistory = (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 } });
+// received; absent → neutral `message` events. An optional `chatLabel` is a stable
+// chat name that scopes the dedupe key so distinct chats don't collide.
+export const importWhatsappHistory = (file, { yourName, chatLabel, ...options } = {}) =>
+ importFile('/timeline/import/whatsapp', file, { ...options, fields: { yourName, chatLabel } });
// Google Takeout Chrome browser history (`History.json`, standalone or zipped) —
// each visit becomes a `web.visit` event (dedupe on a content hash of
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
index 671594ffd2..a1244d8a81 100644
--- a/server/routes/timeline.js
+++ b/server/routes/timeline.js
@@ -70,15 +70,19 @@ const previewField = z.preprocess((v) => {
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.
+// a sent (vs received) message, plus an optional "chat label" — a stable name for
+// the conversation that scopes the content-hash dedupe key so distinct chats don't
+// collide. Both are blank-to-undefined (a blank multipart field means "not
+// provided": yourName → neutral events, chatLabel → legacy un-scoped key) and
+// capped to keep the metadata payload bounded.
+const blankToUndefinedName = z.preprocess(
+ (v) => (typeof v === 'string' && v.trim() === '' ? undefined : v),
+ z.string().max(200).optional(),
+);
const whatsappImportBodySchema = z.object({
preview: previewField,
- yourName: z.preprocess(
- (v) => (typeof v === 'string' && v.trim() === '' ? undefined : v),
- z.string().max(200).optional(),
- ),
+ yourName: blankToUndefinedName,
+ chatLabel: blankToUndefinedName,
});
const dayQuerySchema = z.object({
@@ -148,10 +152,12 @@ router.post('/import/discord', uploadDiscord, importHandler(importDiscordHistory
// POST /api/timeline/import/whatsapp — bulk-backfill a WhatsApp "Export chat"
// 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.
+// classifies direction (sent vs received); absent → neutral `message` events. An
+// optional `chatLabel` scopes the dedupe key to a stable chat name so distinct
+// chats don't collide; absent → the legacy un-scoped key.
router.post('/import/whatsapp', uploadWhatsapp, importHandler(importWhatsappHistory, {
schema: whatsappImportBodySchema,
- toOptions: (body) => ({ dryRun: body.preview, yourName: body.yourName ?? null }),
+ toOptions: (body) => ({ dryRun: body.preview, yourName: body.yourName ?? null, chatLabel: body.chatLabel ?? null }),
}));
// POST /api/timeline/import/browser — bulk-backfill a Google Takeout Chrome
diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.js
index d899b3568a..4f91ded5e8 100644
--- a/server/routes/timeline.test.js
+++ b/server/routes/timeline.test.js
@@ -275,7 +275,7 @@ describe('timeline import routes', () => {
expect(r.body.recorded).toBe(2);
expect(importWhatsappHistory).toHaveBeenCalledWith(
expect.objectContaining({ originalname: 'WhatsApp Chat with Alice.txt' }),
- { dryRun: false, yourName: null },
+ { dryRun: false, yourName: null, chatLabel: null },
);
});
@@ -289,7 +289,7 @@ describe('timeline import routes', () => {
.send(body);
expect(r.status).toBe(200);
expect(r.body.dryRun).toBe(true);
- expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true, yourName: null });
+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true, yourName: null, chatLabel: null });
});
it('whatsapp threads yourName through for direction inference', async () => {
@@ -301,7 +301,7 @@ describe('timeline import routes', () => {
.set('content-type', `multipart/form-data; boundary=${boundary}`)
.send(body);
expect(r.status).toBe(200);
- expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: 'Alice' });
+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: 'Alice', chatLabel: null });
});
it('whatsapp treats a blank yourName field as not provided (neutral)', async () => {
@@ -313,7 +313,29 @@ describe('timeline import routes', () => {
.set('content-type', `multipart/form-data; boundary=${boundary}`)
.send(body);
expect(r.status).toBe(200);
- expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: null });
+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: null, chatLabel: null });
+ });
+
+ it('whatsapp threads chatLabel through as the dedupe scope, blank → null', async () => {
+ const withLabel = multipart(
+ { preview: 'false', chatLabel: 'Family group' },
+ { filename: '_chat.txt', contentType: 'text/plain', content: '[2024-01-15, 6:30:45 PM] Alice: hi\n' },
+ );
+ let r = await request(app).post('/api/timeline/import/whatsapp')
+ .set('content-type', `multipart/form-data; boundary=${withLabel.boundary}`)
+ .send(withLabel.body);
+ expect(r.status).toBe(200);
+ expect(importWhatsappHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false, yourName: null, chatLabel: 'Family group' });
+
+ const blankLabel = multipart(
+ { preview: 'false', chatLabel: ' ' },
+ { filename: '_chat.txt', contentType: 'text/plain', content: '[2024-01-15, 6:30:45 PM] Alice: hi\n' },
+ );
+ r = await request(app).post('/api/timeline/import/whatsapp')
+ .set('content-type', `multipart/form-data; boundary=${blankLabel.boundary}`)
+ .send(blankLabel.body);
+ expect(r.status).toBe(200);
+ expect(importWhatsappHistory).toHaveBeenLastCalledWith(expect.anything(), { dryRun: false, yourName: null, chatLabel: null });
});
it('whatsapp rejects a disallowed file type with 400', async () => {
diff --git a/server/services/whatsappImport.js b/server/services/whatsappImport.js
index c218d94cbc..d812f650da 100644
--- a/server/services/whatsappImport.js
+++ b/server/services/whatsappImport.js
@@ -33,9 +33,21 @@
* 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.
+ * content hash of (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.
+ *
+ * The importer also takes an OPTIONAL `chatLabel`: a stable, user-supplied name for
+ * the conversation (e.g. "Family group"). WhatsApp exports carry no stable chat id
+ * — the filename is unstable (zip vs extracted `_chat.txt`, renames) — so absent a
+ * label the dedupe key is deliberately NOT chat-scoped, which means two DIFFERENT
+ * chats that happen to contain a same-named sender sending an identical body at the
+ * same timestamp granularity collapse into one event. Supplying `chatLabel`
+ * prefixes the hash with that stable scope, so those cross-chat collisions no longer
+ * merge — while a blank label preserves the byte-identical legacy key (backward
+ * compatible). Because the label participates in the key, a chat must be labelled
+ * CONSISTENTLY across re-imports (an unlabelled import and a labelled one of the same
+ * chat are distinct identities); the label also becomes the display chat title.
*/
import { createReadStream } from 'fs';
import { readFile } from 'fs/promises';
@@ -151,12 +163,22 @@ export function normalizeName(name) {
return typeof name === 'string' ? name.trim().toLowerCase() : '';
}
+// Normalize a user-supplied chat label into a stable dedupe scope: trimmed +
+// lower-cased so "Family Group" and " family group " scope to the same chat, or ''
+// for a non-string / empty value (→ the legacy, un-scoped dedupe key). Reuses the
+// same normalization as `normalizeName` so the label is stable across casing/space.
+export function normalizeChatScope(label) {
+ return normalizeName(label);
+}
+
// 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. `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 } = {}) {
+// `chatScope` (optional) is a stable user-supplied chat name folded into the dedupe
+// key so distinct chats don't collide; absent → the legacy un-scoped key.
+export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = null, timezone = null, yourName = null, chatScope = 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')}`
@@ -182,17 +204,20 @@ export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = nul
// but Android lines have none (second defaults to 0), so two identical Android
// messages within the same clock-MINUTE collapse to one event.
//
- // Accepted residual (reviewed, deliberately not "fixed" by re-adding a chat
- // identity): if two DIFFERENT chats both contain a same-named sender sending the
- // same body at the same timestamp granularity, they collapse to one event. A
- // stable chat scope would avoid this, but none exists in a WhatsApp export — the
- // filename is unstable (zip vs extracted `_chat.txt`, renames) and the sender set
- // shifts between a chat's successive full-history exports, so either would
- // REINTRODUCE whole-conversation double-counting, a worse and more common bug
- // than a rare cross-chat single-message collision. Tracked as a #2160 follow-up
- // if a robust chat key ever becomes warranted.
+ // Cross-chat collision residual: without a chat scope, two DIFFERENT chats that
+ // each contain a same-named sender sending the same body at the same timestamp
+ // granularity collapse to one event. The filename-derived chatTitle can't be the
+ // scope (it's unstable across zip-vs-extracted uploads and renames). The optional
+ // `chatScope` (a stable, user-supplied chat name) closes this: when present it is
+ // prefixed into the hash ahead of the ISO instant, so the two chats key apart.
+ // When absent the hash input is byte-identical to the legacy key, so unlabelled
+ // imports (and their idempotency) are unchanged.
+ const scope = normalizeChatScope(chatScope);
+ const hashInput = scope
+ ? `${scope}${happenedAt} ${msg.sender} ${bodyText}`
+ : `${happenedAt} ${msg.sender} ${bodyText}`;
const dedupeKey = createHash('sha1')
- .update(`${happenedAt} ${msg.sender} ${bodyText}`)
+ .update(hashInput)
.digest('hex')
.slice(0, 24);
@@ -214,6 +239,7 @@ export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = nul
dedupeKey: `whatsapp:${dedupeKey}`,
metadata: {
chatTitle: chatTitle || null,
+ chatScope: scope || null,
sender: msg.sender,
hasMedia,
dateOrder: order,
@@ -223,12 +249,13 @@ export function whatsappMessageToCandidate(msg, { order = 'mdy', chatTitle = nul
}
// Map a full parsed chat to candidates: detect the date order once, then map +
-// filter every message under it. `yourName` (optional) classifies direction.
-export function whatsappActivityCandidates(messages = [], { chatTitle = null, timezone = null, yourName = null } = {}) {
+// filter every message under it. `yourName` (optional) classifies direction;
+// `chatScope` (optional) scopes the dedupe key to a stable user-supplied chat name.
+export function whatsappActivityCandidates(messages = [], { chatTitle = null, timezone = null, yourName = null, chatScope = null } = {}) {
if (!Array.isArray(messages)) return [];
const order = detectDateOrder(messages);
return messages
- .map((msg) => whatsappMessageToCandidate(msg, { order, chatTitle, timezone, yourName }))
+ .map((msg) => whatsappMessageToCandidate(msg, { order, chatTitle, timezone, yourName, chatScope }))
.filter(Boolean);
}
@@ -346,12 +373,16 @@ 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, yourName = null } = {}) {
+export async function importWhatsappHistory(file, { dryRun = false, yourName = null, chatLabel = 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, yourName });
+ // A user-supplied chat label (when given) is both the stable dedupe scope AND the
+ // display title, overriding the unstable filename-derived one; absent → fall back
+ // to the filename-derived title with no dedupe scope (legacy behavior).
+ const label = typeof chatLabel === 'string' ? chatLabel.trim() : '';
+ const chatTitle = label || deriveChatTitle(file?.originalname);
+ const candidates = whatsappActivityCandidates(messages, { chatTitle, timezone, yourName, chatScope: label });
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.js
index 143177df37..88c902a105 100644
--- a/server/services/whatsappImport.test.js
+++ b/server/services/whatsappImport.test.js
@@ -6,6 +6,7 @@ import {
whatsappActivityCandidates,
summarizeWhatsappCandidates,
deriveChatTitle,
+ normalizeChatScope,
} from './whatsappImport.js';
// A UTC timezone keeps the offset-less-local → instant resolution deterministic
@@ -166,6 +167,32 @@ describe('whatsappMessageToCandidate', () => {
const sent = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, yourName: 'Alice' });
expect(sent.dedupeKey).toBe(neutral.dedupeKey);
});
+
+ it('leaves the dedupe key byte-identical to the legacy key when no chatScope is given', () => {
+ const withNullScope = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: null });
+ const withBlankScope = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: ' ' });
+ const legacy = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC });
+ expect(withNullScope.dedupeKey).toBe(legacy.dedupeKey);
+ expect(withBlankScope.dedupeKey).toBe(legacy.dedupeKey);
+ expect(legacy.metadata.chatScope).toBeNull();
+ });
+
+ it('scopes the dedupe key by chatScope so distinct chats do not collide', () => {
+ const unscoped = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC });
+ const family = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: 'Family group' });
+ const work = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: 'Work chat' });
+ // Same message, different chat scopes → three distinct dedupe keys.
+ expect(family.dedupeKey).not.toBe(unscoped.dedupeKey);
+ expect(work.dedupeKey).not.toBe(unscoped.dedupeKey);
+ expect(family.dedupeKey).not.toBe(work.dedupeKey);
+ expect(family.metadata.chatScope).toBe('family group');
+ });
+
+ it('normalizes chatScope (case/space-insensitive) so a chat labels stably across imports', () => {
+ const a = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: 'Family Group' });
+ const b = whatsappMessageToCandidate(msg, { order: 'ymd', timezone: UTC, chatScope: ' family group ' });
+ expect(a.dedupeKey).toBe(b.dedupeKey);
+ });
});
describe('whatsappActivityCandidates', () => {
@@ -183,6 +210,15 @@ describe('whatsappActivityCandidates', () => {
expect(alice.kind).toBe('message.sent');
expect(bob.kind).toBe('message.received');
});
+ it('threads chatScope through the batch so the same messages key apart per chat', () => {
+ const msgs = parseWhatsappChat(androidChat);
+ const chatA = whatsappActivityCandidates(msgs, { timezone: UTC, chatScope: 'Chat A' });
+ const chatB = whatsappActivityCandidates(msgs, { timezone: UTC, chatScope: 'Chat B' });
+ const unscoped = whatsappActivityCandidates(msgs, { timezone: UTC });
+ expect(chatA.map((c) => c.dedupeKey)).not.toEqual(chatB.map((c) => c.dedupeKey));
+ expect(chatA.map((c) => c.dedupeKey)).not.toEqual(unscoped.map((c) => c.dedupeKey));
+ expect(chatA.every((c) => c.metadata.chatScope === 'chat a')).toBe(true);
+ });
it('returns [] for non-arrays', () => {
expect(whatsappActivityCandidates(null)).toEqual([]);
expect(whatsappActivityCandidates({})).toEqual([]);
@@ -229,3 +265,17 @@ describe('deriveChatTitle', () => {
expect(deriveChatTitle('my-export.txt')).toBe('my-export');
});
});
+
+describe('normalizeChatScope', () => {
+ it('trims and lower-cases a label so it is stable across casing/space', () => {
+ expect(normalizeChatScope(' Family Group ')).toBe('family group');
+ expect(normalizeChatScope('WORK')).toBe('work');
+ });
+ it('returns "" for a blank or non-string value (→ legacy un-scoped key)', () => {
+ expect(normalizeChatScope('')).toBe('');
+ expect(normalizeChatScope(' ')).toBe('');
+ expect(normalizeChatScope(null)).toBe('');
+ expect(normalizeChatScope(undefined)).toBe('');
+ expect(normalizeChatScope(42)).toBe('');
+ });
+});