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(timeline): Discord data-package bulk-history importer (#2160)
Adam Eivy4dd9902df882
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0a220717d6..97d17c90ee 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 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`)- **[issue-2160] Bulk-history importer for Spotify extended streaming history + shared import seam.** The `/timeline` page gains a collapsible "Import Spotify history" panel: upload the privacy-download ZIP (or a single `Streaming_History_Audio_*.json`) → preview parsed counts/date-range/top-artists → confirm, and every play lands as an idempotent `media.listen` event via the existing `recordEvents()` infra (dedupe on track-uri + played-at, so re-imports and overlapping exports never double-count). Both the modern extended-history shape (`ts`/`ms_played`/`master_metadata_*`) and the legacy `StreamingHistory*.json` shape (`endTime`/`artistName`/`trackName`/`msPlayed`) are parsed; legacy offset-less UTC timestamps are anchored to UTC so a server west of UTC can't shift the listen into the wrong day. The route reuses the streaming `multipart.js` parser + `zipStream.js` (no new deps; the JSON parser is hand-written), Zod-validates the `preview` flag, and always unlinks the temp upload. This is one slice of the larger backfill issue. (`server/services/spotifyImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/SpotifyImportPanel.jsx`, `client/src/pages/Timeline.jsx`)diff --git a/client/src/components/timeline/DiscordImportPanel.jsx b/client/src/components/timeline/DiscordImportPanel.jsxnew file mode 100644index 0000000000..2a1d657b38--- /dev/null+++ b/client/src/components/timeline/DiscordImportPanel.jsx@@ -0,0 +1,39 @@+import { MessageSquare } from 'lucide-react';+import * as api from '../../services/api';+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';++// Bulk-backfill importer for the Discord "data package" export (#2160) → the+// messages you sent across every channel/DM as message.sent events, built on the+// shared ActivityImportPanel seam.+export default function DiscordImportPanel({ onImported }) {+ return (+ <ActivityImportPanel+ icon={MessageSquare}+ title="Import Discord history"+ noun="message"+ importFn={api.importDiscordHistory}+ onImported={onImported}+ help={(+ <>+ Request your <span className="text-gray-300">data package</span> from Discord+ (Settings → Data & Privacy → Request all of my Data), then upload the ZIP (or a+ single <span className="font-mono">messages.json</span>/<span className="font-mono">.csv</span>)+ here. Only the messages you sent are imported. Re-imports are safe.+ </>+ )}+ renderPreview={(summary) => (+ <>+ <div>{summary.messages} message(s) across {summary.uniqueChannels} channel(s)</div>+ {dateRangeLabel(summary.from, summary.to) && (+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</div>+ )}+ {summary.topChannels?.length > 0 && (+ <div className="mt-1 truncate">+ Top: {summary.topChannels.slice(0, 5).map((c) => c.name).join(', ')}+ </div>+ )}+ </>+ )}+ />+ );+}diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsxindex 1c5b6313be..b1f8aeae4c 100644--- a/client/src/pages/Timeline.jsx+++ b/client/src/pages/Timeline.jsx@@ -7,6 +7,7 @@ import {import PageHeader from '../components/PageHeader';import SpotifyImportPanel from '../components/timeline/SpotifyImportPanel';import TakeoutLocationImportPanel from '../components/timeline/TakeoutLocationImportPanel';+import DiscordImportPanel from '../components/timeline/DiscordImportPanel';import * as api from '../services/api';import toast from '../components/ui/Toast';import { formatClockTime, formatDurationSec } from '../utils/formatters';@@ -39,6 +40,7 @@ const SOURCE_ICON = {spotify: Music,youtube: Play,location: MapPin,+ discord: MessageSquare,};function kindIcon(kind, source) {@@ -207,6 +209,7 @@ export default function Timeline() {<SpotifyImportPanel onImported={() => setReloadKey((k) => k + 1)} /><TakeoutLocationImportPanel onImported={() => setReloadKey((k) => k + 1)} />+ <DiscordImportPanel onImported={() => setReloadKey((k) => k + 1)} /><Histogram histogram={histogram} />diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.jsindex 1d29443e4a..490e9ce49a 100644--- a/client/src/services/apiTimeline.js+++ b/client/src/services/apiTimeline.js@@ -40,3 +40,8 @@ export const importSpotifyHistory = (file, options = {}) =>// visit-start + place identity).export const importTakeoutLocationHistory = (file, options = {}) =>importFile('/timeline/import/takeout-location', file, options);++// Discord "data package" — the messages you sent across every channel/DM+// (dedupe on the globally-unique Discord message snowflake id).+export const importDiscordHistory = (file, options = {}) =>+ importFile('/timeline/import/discord', file, options);diff --git a/server/routes/timeline.js b/server/routes/timeline.jsindex edda35b529..47b21da0c8 100644--- a/server/routes/timeline.js+++ b/server/routes/timeline.js@@ -8,6 +8,7 @@ import { uploadSingle } from '../lib/multipart.js';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';const router = Router();@@ -26,6 +27,17 @@ const zipOrJsonUpload = (label) => uploadSingle('file', {const uploadSpotify = zipOrJsonUpload('Spotify');const uploadTakeoutLocation = zipOrJsonUpload('Google Takeout location');+// The Discord data package ships `messages.csv` in older exports, so accept CSV+// alongside the ZIP/JSON the other importers take.+const uploadDiscord = uploadSingle('file', {+ limits: { fileSize: 200 * 1024 * 1024 },+ fileFilter: (req, file, cb) => {+ const ok = /\.(zip|json|csv)$/i.test(file.originalname)+ || ['application/zip', 'application/x-zip-compressed', 'application/json', 'text/json', 'text/csv', 'application/csv'].includes(file.mimetype);+ if (ok) return cb(null, true);+ cb(new ServerError('Only Discord data-package ZIP, JSON, or CSV 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@@ -96,4 +108,9 @@ router.post('/import/spotify', uploadSpotify, importHandler(importSpotifyHistory// (dedupe on visit-start + place identity).router.post('/import/takeout-location', uploadTakeoutLocation, importHandler(importTakeoutLocationHistory));+// POST /api/timeline/import/discord — bulk-backfill a Discord "data package"+// (the messages you sent across every channel/DM) → message.sent events+// (dedupe on the globally-unique Discord message snowflake id).+router.post('/import/discord', uploadDiscord, importHandler(importDiscordHistory));+export default router;diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.jsindex 838bb29a21..56eaf7fd65 100644--- a/server/routes/timeline.test.js+++ b/server/routes/timeline.test.js@@ -27,6 +27,17 @@ vi.mock('../services/takeoutLocationImport.js', () => ({})),}));+vi.mock('../services/discordImport.js', () => ({+ importDiscordHistory: vi.fn(async (file, opts) => ({+ dryRun: Boolean(opts?.dryRun),+ parsed: 4,+ mapped: 4,+ recorded: opts?.dryRun ? 0 : 4,+ skipped: opts?.dryRun ? 0 : 0,+ summary: { messages: 4, uniqueChannels: 2, from: null, to: null, topChannels: [] },+ })),+}));+vi.mock('../services/humanActivity.js', () => ({getDaySummary: vi.fn(async () => ({ date: '2026-07-07', events: [] })),listEvents: vi.fn(async () => []),@@ -34,6 +45,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 timelineRoutes from './timeline.js';function makeApp() {@@ -185,4 +197,45 @@ describe('timeline import routes', () => {expect(r.status).toBe(400);expect(importTakeoutLocationHistory).not.toHaveBeenCalled();});++ it('POST /import/discord parses the upload and calls the importer', async () => {+ const { boundary, body } = multipart(+ { preview: 'false' },+ { filename: 'package.zip', contentType: 'application/zip', content: 'PK...' },+ );+ const r = await request(app).post('/api/timeline/import/discord')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body.recorded).toBe(4);+ expect(importDiscordHistory).toHaveBeenCalledWith(+ expect.objectContaining({ originalname: 'package.zip' }),+ { dryRun: false },+ );+ });++ it('discord accepts a messages.csv upload', async () => {+ const { boundary, body } = multipart(+ { preview: 'true' },+ { filename: 'messages.csv', contentType: 'text/csv', content: 'ID,Timestamp\n1,2023-01-01 00:00:00\n' },+ );+ const r = await request(app).post('/api/timeline/import/discord')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body.dryRun).toBe(true);+ expect(importDiscordHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });+ });++ it('discord rejects a disallowed file type with 400', async () => {+ const { boundary, body } = multipart(+ {},+ { filename: 'notes.txt', contentType: 'text/plain', content: 'hi' },+ );+ const r = await request(app).post('/api/timeline/import/discord')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(400);+ expect(importDiscordHistory).not.toHaveBeenCalled();+ });});diff --git a/server/services/discordImport.js b/server/services/discordImport.jsnew file mode 100644index 0000000000..f679016ddc--- /dev/null+++ b/server/services/discordImport.js@@ -0,0 +1,296 @@+/**+ * Discord data-package importer (#2160) — bulk historical backfill into the+ * human-activity timeline.+ *+ * Discord's "Request my data" download ships a ZIP whose `messages/` folder holds+ * ONE subfolder per channel/DM you participated in. Each subfolder carries:+ * - `channel.json` — channel metadata `{ id, type, name?, guild?: { id, name },+ * recipients?: [...] }` (recipients are the *other* people in a DM).+ * - `messages.json` (2023+) or `messages.csv` (older) — an array of the messages+ * YOU sent in that channel: `{ ID, Timestamp, Contents, Attachments }`.+ *+ * Every message in a Discord data package is authored by the account owner, so+ * the direction is unambiguous: each maps to a `message.sent` activity event+ * under source `discord`. Contents keep only a SHORT summary line (privacy+ * contract); the message id + channel id in `metadata` point back to the source.+ *+ * Idempotent: Discord message IDs are globally-unique snowflakes, so the dedupe+ * key is just `discord:<messageId>` — re-importing the same export (or a newer+ * overlapping one) 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 { parseZip, collectZipEntry } from '../lib/zipStream.js';+import { shortSummary, recordEvents, normalizeParticipants } from './humanActivity.js';++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).+// ---------------------------------------------------------------------------++// Resolve a Discord message timestamp to a UTC ISO string, or null if+// unparseable. Newer exports use ISO-8601 with an offset+// (`2023-05-01T18:30:45.123+00:00`); older CSV exports use a space-separated UTC+// wall clock (`2023-05-01 18:30:45`) — append the missing `Z` so it's read as+// UTC, not the server's OS-local zone.+export function resolveDiscordInstant(value) {+ if (value === null || value === undefined) return null;+ const s = String(value).trim();+ if (!s) return null;+ const legacy = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/.exec(s);+ const iso = legacy ? `${legacy[1]}T${legacy[2]}Z` : s;+ const d = new Date(iso);+ return Number.isNaN(d.getTime()) ? null : d.toISOString();+}++// Minimal RFC-4180 CSV parser (written in-tree to avoid a dependency for one+// helper). Handles quoted fields, escaped quotes (`""`), and embedded+// commas/newlines. Returns an array of row objects keyed by the header row.+// Discord's older `messages.csv` is exactly this shape: `ID,Timestamp,Contents,+// Attachments` with the Contents column freely containing commas and newlines.+export function parseCsv(text) {+ const rows = [];+ let field = '';+ let row = [];+ let inQuotes = false;+ const s = String(text ?? '');+ for (let i = 0; i < s.length; i += 1) {+ const ch = s[i];+ if (inQuotes) {+ if (ch === '"') {+ if (s[i + 1] === '"') { field += '"'; i += 1; } // escaped quote+ else inQuotes = false;+ } else {+ field += ch;+ }+ continue;+ }+ if (ch === '"') { inQuotes = true; continue; }+ if (ch === ',') { row.push(field); field = ''; continue; }+ if (ch === '\r') continue; // normalize CRLF → LF+ if (ch === '\n') { row.push(field); rows.push(row); field = ''; row = []; continue; }+ field += ch;+ }+ // Flush the trailing field/row when the file doesn't end in a newline.+ if (field.length > 0 || row.length > 0) { row.push(field); rows.push(row); }+ if (rows.length === 0) return [];+ const header = rows[0].map((h) => h.trim());+ return rows.slice(1).map((cols) => {+ const obj = {};+ header.forEach((key, idx) => { obj[key] = cols[idx] ?? ''; });+ return obj;+ });+}++// Parse the text of ONE Discord `messages.json` / `messages.csv` file into a raw+// record array. JSON is a top-level array (or `{ messages: [...] }` wrapper);+// CSV is dispatched by a leading `ID,` header. Throws only on malformed JSON.+export function parseDiscordMessagesText(text, entryPath = '') {+ const s = String(text ?? '');+ if (/\.csv$/i.test(entryPath) || /^\s*id\s*,/i.test(s)) return parseCsv(s);+ const parsed = JSON.parse(s);+ if (Array.isArray(parsed)) return parsed;+ if (Array.isArray(parsed?.messages)) return parsed.messages;+ return [];+}++// Build a human-friendly channel label from a parsed `channel.json`. A guild+// channel reads "Guild — #channel"; a DM reads "DM with A, B"; anything else+// falls back to the channel name or id.+export function channelLabel(channel) {+ if (!channel || typeof channel !== 'object') return null;+ const guildName = channel.guild?.name;+ if (guildName) return channel.name ? `${guildName} — #${channel.name}` : guildName;+ const recips = Array.isArray(channel.recipients) ? channel.recipients : [];+ const names = recips.map((r) => (typeof r === 'string' ? r : r?.username || r?.name)).filter(Boolean);+ if (names.length) return `DM with ${names.join(', ')}`;+ return channel.name || (channel.id ? `Channel ${channel.id}` : null);+}++// Map ONE raw Discord message record (+ optional resolved channel context) to an+// activity candidate, or null if it lacks a usable id or timestamp. Column names+// come straight from Discord's export (`ID`, `Timestamp`, `Contents`,+// `Attachments`); lowercase variants are tolerated for forward-compat.+export function discordMessageToCandidate(record, channel = null) {+ if (!record || typeof record !== 'object') return null;+ const messageId = String(record.ID ?? record.id ?? '').trim();+ if (!messageId) return null;+ const happenedAt = resolveDiscordInstant(record.Timestamp ?? record.timestamp);+ if (!happenedAt) return null;++ const contents = record.Contents ?? record.contents ?? '';+ const attachmentsRaw = record.Attachments ?? record.attachments ?? '';+ const hasAttachments = Array.isArray(attachmentsRaw)+ ? attachmentsRaw.length > 0+ : Boolean(String(attachmentsRaw).trim());++ const label = channelLabel(channel);+ const channelId = channel?.id || record.channelId || null;+ // A message with no text (attachment-only) still carries autobiographical+ // signal (you sent something at this time) — keep it, with a placeholder body.+ const summaryText = String(contents).trim() || (hasAttachments ? '(attachment)' : '');++ return {+ source: 'discord',+ kind: 'message.sent',+ happenedAt,+ title: label || 'Discord message',+ summary: shortSummary(summaryText),+ participants: normalizeParticipants(+ (Array.isArray(channel?.recipients) ? channel.recipients : [])+ .map((r) => (typeof r === 'string' ? { name: r } : { name: r?.username || r?.name })),+ ),+ dedupeKey: `discord:${messageId}`,+ metadata: {+ messageId,+ channelId,+ channelName: label,+ guildName: channel?.guild?.name || null,+ channelType: channel?.type ?? null,+ hasAttachments,+ },+ };+}++// Map a batch of { record, channel } intermediates to candidates, dropping the+// unmappable ones.+export function discordActivityCandidates(items = []) {+ if (!Array.isArray(items)) return [];+ return items.map((it) => discordMessageToCandidate(it.record, it.channel)).filter(Boolean);+}++// Summarize a candidate batch for the import preview: date range, message count,+// unique channels, and the most-active channel labels. Pure over candidates.+export function summarizeDiscordCandidates(candidates = []) {+ const list = Array.isArray(candidates) ? candidates : [];+ let earliest = null;+ let latest = null;+ const channels = new Set();+ const channelCounts = 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;+ }+ // Group by channel identity (id when present, else the label) so the unique+ // count can't diverge from the top-channels tally below.+ const identity = c.metadata?.channelId || c.metadata?.channelName || c.title;+ channels.add(identity);+ const label = c.metadata?.channelName || c.title;+ channelCounts.set(label, (channelCounts.get(label) || 0) + 1);+ }+ const topChannels = [...channelCounts.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ .map(([name, count]) => ({ name, count }));+ return {+ messages: list.length,+ uniqueChannels: channels.size,+ from: earliest,+ to: latest,+ topChannels,+ };+}++// ---------------------------------------------------------------------------+// File ingestion (ZIP data package or single messages JSON/CSV) → intermediates.+// ---------------------------------------------------------------------------++const isZip = (file) =>+ file?.mimetype === 'application/zip' ||+ file?.mimetype === 'application/x-zip-compressed' ||+ /\.zip$/i.test(file?.originalname || '');++// The directory token identifying a channel within the package (`messages/c123/…`+// or the newer `messages/123/…`) — the grouping key that joins a channel's+// `channel.json` to its `messages.(json|csv)`.+const channelDirOf = (entryPath) => {+ const m = /(?:^|\/)messages\/([^/]+)\/(?:messages\.(?:json|csv)|channel\.json)$/i.exec(String(entryPath || ''));+ return m ? m[1] : null;+};+const isMessagesEntry = (entryPath) => /(?:^|\/)messages\/[^/]+\/messages\.(?:json|csv)$/i.test(String(entryPath || ''));+const isChannelJsonEntry = (entryPath) => /(?:^|\/)messages\/[^/]+\/channel\.json$/i.test(String(entryPath || ''));++// Extract { record, channel } intermediates from the Discord data-package ZIP.+// Both the per-channel `channel.json` and `messages.*` files are collected into+// per-directory maps (either may stream first), then joined after close so every+// message carries its channel's context.+async function readItemsFromZip(filePath) {+ const channels = new Map(); // dir → parsed channel.json+ const messagesByDir = new Map(); // dir → raw message records[]+ 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 read + parse pipeline so a large upload with an+ // early error (bad JSON member, corrupt ZIP) 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) => {+ const dir = channelDirOf(entry.path);+ if (dir && isMessagesEntry(entry.path)) {+ const entryPath = entry.path;+ reads.push(+ collectZipEntry(entry)+ .then((buf) => {+ const recs = parseDiscordMessagesText(buf.toString('utf-8'), entryPath);+ const existing = messagesByDir.get(dir) || [];+ messagesByDir.set(dir, existing.concat(recs));+ })+ .catch(settle(reject)),+ );+ } else if (dir && isChannelJsonEntry(entry.path)) {+ reads.push(+ collectZipEntry(entry)+ .then((buf) => { channels.set(dir, JSON.parse(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));+ });+ const items = [];+ for (const [dir, recs] of messagesByDir) {+ const channel = channels.get(dir) || null;+ for (const record of recs) items.push({ record, channel });+ }+ return items;+}++// Read { record, channel } intermediates from an uploaded file (the full ZIP+// data package, or a single `messages.json` / `messages.csv` with no channel+// context).+export async function readDiscordItems(file) {+ if (!file?.path) return [];+ if (isZip(file)) return readItemsFromZip(file.path);+ const text = await readFile(file.path, 'utf-8');+ return parseDiscordMessagesText(text, file.originalname || '').map((record) => ({ record, channel: null }));+}++// End-to-end import seam: read the file → map → (preview | record). Returns+// counts + a preview summary. `dryRun` parses and summarizes WITHOUT writing so+// the UI can show the user what will be imported before they commit. Because+// `recordEvents` is idempotent, committing (or re-committing) is always safe.+export async function importDiscordHistory(file, { dryRun = false } = {}) {+ const items = await readDiscordItems(file);+ const candidates = discordActivityCandidates(items);+ const summary = summarizeDiscordCandidates(candidates);+ if (dryRun) {+ console.log(`💬 Discord import preview: ${candidates.length} message(s) from ${items.length} record(s)`);+ return { dryRun: true, parsed: items.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };+ }+ const { recorded, skipped } = await recordEvents(candidates);+ console.log(`💬 Discord import: ${recorded} new message(s) recorded, ${skipped} duplicate/invalid (from ${items.length} record(s))`);+ return { dryRun: false, parsed: items.length, mapped: candidates.length, recorded, skipped, summary };+}diff --git a/server/services/discordImport.test.js b/server/services/discordImport.test.jsnew file mode 100644index 0000000000..ba13a0604a--- /dev/null+++ b/server/services/discordImport.test.js@@ -0,0 +1,193 @@+import { describe, it, expect } from 'vitest';+import {+ resolveDiscordInstant,+ parseCsv,+ parseDiscordMessagesText,+ channelLabel,+ discordMessageToCandidate,+ discordActivityCandidates,+ summarizeDiscordCandidates,+} from './discordImport.js';++// A representative newer-export (messages.json) record.+const jsonRecord = {+ ID: '1103456789012345678',+ Timestamp: '2023-05-01T18:30:45.123+00:00',+ Contents: 'hey did you see the game last night?',+ Attachments: '',+};++// A guild channel context (channel.json).+const guildChannel = {+ id: '900000000000000001',+ type: 0,+ name: 'general',+ guild: { id: '800000000000000001', name: 'Dev Server' },+};++// A DM channel context.+const dmChannel = {+ id: '900000000000000002',+ type: 1,+ recipients: [{ username: 'alice' }, { username: 'bob' }],+};++describe('resolveDiscordInstant', () => {+ it('passes ISO-8601 timestamps with an offset straight through', () => {+ expect(resolveDiscordInstant('2023-05-01T18:30:45.123+00:00')).toBe('2023-05-01T18:30:45.123Z');+ });+ it('interprets legacy space-separated CSV timestamps as UTC (not OS-local)', () => {+ expect(resolveDiscordInstant('2023-05-01 18:30:45')).toBe('2023-05-01T18:30:45.000Z');+ });+ it('returns null for empty/unparseable values', () => {+ expect(resolveDiscordInstant('')).toBeNull();+ expect(resolveDiscordInstant(null)).toBeNull();+ expect(resolveDiscordInstant('not a date')).toBeNull();+ });+});++describe('parseCsv', () => {+ it('parses a header + rows into keyed objects', () => {+ const rows = parseCsv('ID,Timestamp,Contents,Attachments\n1,2023-05-01 18:30:45,hi,\n');+ expect(rows).toHaveLength(1);+ expect(rows[0]).toEqual({ ID: '1', Timestamp: '2023-05-01 18:30:45', Contents: 'hi', Attachments: '' });+ });+ it('handles quoted fields with embedded commas, quotes, and newlines', () => {+ const csv = 'ID,Contents\n1,"a, b, ""c""\nsecond line"\n';+ const rows = parseCsv(csv);+ expect(rows).toHaveLength(1);+ expect(rows[0].Contents).toBe('a, b, "c"\nsecond line');+ });+ it('flushes a trailing row with no final newline', () => {+ const rows = parseCsv('ID,Contents\n1,hi');+ expect(rows).toHaveLength(1);+ expect(rows[0].ID).toBe('1');+ });+ it('returns [] for empty input', () => {+ expect(parseCsv('')).toEqual([]);+ });+});++describe('parseDiscordMessagesText', () => {+ it('parses a top-level JSON array', () => {+ expect(parseDiscordMessagesText(JSON.stringify([jsonRecord]))).toHaveLength(1);+ });+ it('unwraps a { messages: [...] } shape', () => {+ expect(parseDiscordMessagesText(JSON.stringify({ messages: [jsonRecord] }))).toHaveLength(1);+ });+ it('dispatches to CSV on a .csv entry path', () => {+ const rows = parseDiscordMessagesText('ID,Timestamp,Contents\n1,2023-01-01 00:00:00,hi\n', 'messages/c1/messages.csv');+ expect(rows).toHaveLength(1);+ expect(rows[0].Contents).toBe('hi');+ });+ it('dispatches to CSV on a leading ID, header even without a path', () => {+ const rows = parseDiscordMessagesText('ID,Timestamp\n1,2023-01-01 00:00:00\n');+ expect(rows).toHaveLength(1);+ });+ it('returns [] for a non-array/object JSON shape', () => {+ expect(parseDiscordMessagesText('42')).toEqual([]);+ expect(parseDiscordMessagesText('{"foo":1}')).toEqual([]);+ });+ it('throws on malformed JSON', () => {+ expect(() => parseDiscordMessagesText('{not json')).toThrow();+ });+});++describe('channelLabel', () => {+ it('labels a guild channel as "Guild — #channel"', () => {+ expect(channelLabel(guildChannel)).toBe('Dev Server — #general');+ });+ it('labels a DM by its recipients', () => {+ expect(channelLabel(dmChannel)).toBe('DM with alice, bob');+ });+ it('falls back to the channel name/id, then null', () => {+ expect(channelLabel({ name: 'lonely' })).toBe('lonely');+ expect(channelLabel({ id: '42' })).toBe('Channel 42');+ expect(channelLabel(null)).toBeNull();+ });+});++describe('discordMessageToCandidate', () => {+ it('maps a JSON record + guild channel to a message.sent candidate', () => {+ const c = discordMessageToCandidate(jsonRecord, guildChannel);+ expect(c).toMatchObject({+ source: 'discord',+ kind: 'message.sent',+ happenedAt: '2023-05-01T18:30:45.123Z',+ title: 'Dev Server — #general',+ });+ expect(c.summary).toBe('hey did you see the game last night?');+ expect(c.metadata).toMatchObject({+ messageId: '1103456789012345678',+ channelId: '900000000000000001',+ guildName: 'Dev Server',+ hasAttachments: false,+ });+ });++ it('builds a stable dedupe key from the message snowflake id', () => {+ const c1 = discordMessageToCandidate(jsonRecord, guildChannel);+ const c2 = discordMessageToCandidate({ ...jsonRecord }, dmChannel);+ // Same message id → same dedupe key regardless of channel context.+ expect(c1.dedupeKey).toBe('discord:1103456789012345678');+ expect(c1.dedupeKey).toBe(c2.dedupeKey);+ });++ it('carries DM recipients as participants', () => {+ const c = discordMessageToCandidate(jsonRecord, dmChannel);+ expect(c.participants).toEqual([{ name: 'alice' }, { name: 'bob' }]);+ });++ it('keeps an attachment-only message with a placeholder body', () => {+ const c = discordMessageToCandidate(+ { ID: '9', Timestamp: '2023-01-01 00:00:00', Contents: '', Attachments: 'https://cdn/x.png' },+ null,+ );+ expect(c.summary).toBe('(attachment)');+ expect(c.metadata.hasAttachments).toBe(true);+ expect(c.title).toBe('Discord message');+ });++ it('drops records with no id or no timestamp', () => {+ expect(discordMessageToCandidate({ Timestamp: '2023-01-01 00:00:00' })).toBeNull();+ expect(discordMessageToCandidate({ ID: '1' })).toBeNull();+ expect(discordMessageToCandidate(null)).toBeNull();+ });+});++describe('discordActivityCandidates', () => {+ it('maps a batch of { record, channel } intermediates and filters unmappable rows', () => {+ const out = discordActivityCandidates([+ { record: jsonRecord, channel: guildChannel },+ { record: { ID: '2' }, channel: null }, // no timestamp → dropped+ { record: { ID: '3', Timestamp: '2023-02-02 12:00:00', Contents: 'yo' }, channel: dmChannel },+ ]);+ expect(out).toHaveLength(2);+ expect(out.every((c) => c.source === 'discord' && c.kind === 'message.sent')).toBe(true);+ });+ it('returns [] for non-arrays', () => {+ expect(discordActivityCandidates(null)).toEqual([]);+ expect(discordActivityCandidates({})).toEqual([]);+ });+});++describe('summarizeDiscordCandidates', () => {+ it('computes range, message count, unique channels, and top channels', () => {+ const candidates = discordActivityCandidates([+ { record: jsonRecord, channel: guildChannel },+ { record: { ID: '2', Timestamp: '2022-01-01 09:00:00', Contents: 'earlier' }, channel: guildChannel },+ { record: { ID: '3', Timestamp: '2023-06-01 10:00:00', Contents: 'dm' }, channel: dmChannel },+ ]);+ const s = summarizeDiscordCandidates(candidates);+ expect(s.messages).toBe(3);+ expect(s.uniqueChannels).toBe(2);+ expect(s.from).toBe('2022-01-01T09:00:00.000Z');+ expect(s.to).toBe('2023-06-01T10:00:00.000Z');+ expect(s.topChannels[0]).toEqual({ name: 'Dev Server — #general', count: 2 });+ });+ it('handles an empty batch', () => {+ const s = summarizeDiscordCandidates([]);+ expect(s).toMatchObject({ messages: 0, uniqueChannels: 0, from: null, to: null });+ expect(s.topChannels).toEqual([]);+ });+});