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: bulk-history importer for browser history → timeline web.visit events (#2160)
Adam Eivyd77cfac1cec5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d0da96bd36..584069bb51 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -156,6 +156,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 browser history → timeline `web.visit` events, on the shared import seam.** The `/timeline` page gains a collapsible "Import browser history" panel alongside the Spotify, location, Discord, and WhatsApp ones: request the **Chrome** product from Google Takeout (takeout.google.com), then upload the ZIP (or a single `History.json`) → preview parsed visit counts + unique sites + date-range + top domains → confirm, and every page visit lands as an idempotent `web.visit` event (source `browser`) via the existing `recordEvents()` infra. Chromium browsers have no in-app history export, so Takeout's `History.json` (or the older `BrowserHistory.json`) is the ingestion path; `time_usec` is epoch-microseconds (UTC, already normalized by Takeout) → divided to ms for the instant. The full URL lands in the row's `url` column while the summary keeps only the hostname (privacy contract — no query strings in the preview line). Subframe navigations (`AUTO_SUBFRAME`/`MANUAL_SUBFRAME` — ad/embed iframe loads Chrome records alongside real navigations) are dropped as noise, the same way the location importer drops travel segments. Since a visit carries no id in the export, the dedupe key is a stable content hash of (visit-instant + URL), 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/browserHistoryImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/BrowserHistoryImportPanel.jsx`, `client/src/pages/Timeline.jsx`)+- **[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`)diff --git a/client/src/components/timeline/BrowserHistoryImportPanel.jsx b/client/src/components/timeline/BrowserHistoryImportPanel.jsxnew file mode 100644index 0000000000..875783bf1f--- /dev/null+++ b/client/src/components/timeline/BrowserHistoryImportPanel.jsx@@ -0,0 +1,38 @@+import { Globe } from 'lucide-react';+import * as api from '../../services/api';+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';++// Bulk-backfill importer for Google Takeout Chrome browser history (#2160) →+// web.visit events, built on the shared ActivityImportPanel seam.+export default function BrowserHistoryImportPanel({ onImported }) {+ return (+ <ActivityImportPanel+ icon={Globe}+ title="Import browser history"+ noun="visit"+ importFn={api.importBrowserHistory}+ onImported={onImported}+ help={(+ <>+ Request <span className="text-gray-300">Chrome</span> from Google Takeout+ (takeout.google.com), then upload the ZIP (or a single+ <span className="font-mono"> History.json</span>) here. Each page visit is+ imported; ad/embed iframe loads are skipped. Re-imports are safe.+ </>+ )}+ renderPreview={(summary) => (+ <>+ <div>{summary.visits} visit(s) across {summary.uniqueHosts} unique site(s)</div>+ {dateRangeLabel(summary.from, summary.to) && (+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</div>+ )}+ {summary.topHosts?.length > 0 && (+ <div className="mt-1 truncate">+ Top: {summary.topHosts.slice(0, 5).map((h) => h.name).join(', ')}+ </div>+ )}+ </>+ )}+ />+ );+}diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsxindex 4fb4fad84b..e56670dba5 100644--- a/client/src/pages/Timeline.jsx+++ b/client/src/pages/Timeline.jsx@@ -2,13 +2,14 @@ import { useState, useEffect, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';import {CalendarClock, ChevronLeft, ChevronRight, Mail, MailOpen, Send,- CalendarDays, Music, Play, MessageSquare, Activity, MapPin,+ CalendarDays, Music, Play, MessageSquare, Activity, MapPin, Globe,} from 'lucide-react';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 BrowserHistoryImportPanel from '../components/timeline/BrowserHistoryImportPanel';import * as api from '../services/api';import toast from '../components/ui/Toast';import { formatClockTime, formatDurationSec } from '../utils/formatters';@@ -42,6 +43,7 @@ const SOURCE_ICON = {youtube: Play,location: MapPin,discord: MessageSquare,+ browser: Globe,};function kindIcon(kind, source) {@@ -49,6 +51,7 @@ function kindIcon(kind, source) {if (kind === 'message.received') return MailOpen;if (kind === 'calendar.event') return CalendarDays;if (kind === 'place.visit') return MapPin;+ if (kind === 'web.visit') return Globe;return SOURCE_ICON[source] || Activity;}@@ -57,7 +60,8 @@ function KindBadge({ kind }) {: kind === 'message.received' ? 'Received': kind === 'calendar.event' ? 'Event': kind === 'place.visit' ? 'Visit'- : kind;+ : kind === 'web.visit' ? 'Web'+ : kind;return (<span className="rounded bg-port-bg px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-gray-400">{label}@@ -212,6 +216,7 @@ export default function Timeline() {<TakeoutLocationImportPanel onImported={() => setReloadKey((k) => k + 1)} /><DiscordImportPanel onImported={() => setReloadKey((k) => k + 1)} /><WhatsappImportPanel onImported={() => setReloadKey((k) => k + 1)} />+ <BrowserHistoryImportPanel onImported={() => setReloadKey((k) => k + 1)} /><Histogram histogram={histogram} />diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.jsindex 090319ffca..e329452104 100644--- a/client/src/services/apiTimeline.js+++ b/client/src/services/apiTimeline.js@@ -57,3 +57,9 @@ export const importDiscordHistory = (file, options = {}) =>// received; absent → neutral `message` events.export const importWhatsappHistory = (file, { yourName, ...options } = {}) =>importFile('/timeline/import/whatsapp', file, { ...options, fields: { yourName } });++// Google Takeout Chrome browser history (`History.json`, standalone or zipped) —+// each visit becomes a `web.visit` event (dedupe on a content hash of+// visit-instant + URL). Subframe (iframe) loads are dropped server-side.+export const importBrowserHistory = (file, options = {}) =>+ importFile('/timeline/import/browser', file, options);diff --git a/server/routes/timeline.js b/server/routes/timeline.jsindex c2f4023c6a..671594ffd2 100644--- a/server/routes/timeline.js+++ b/server/routes/timeline.js@@ -10,6 +10,7 @@ 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 { importBrowserHistory } from '../services/browserHistoryImport.js';const router = Router();@@ -28,6 +29,9 @@ const zipOrJsonUpload = (label) => uploadSingle('file', {const uploadSpotify = zipOrJsonUpload('Spotify');const uploadTakeoutLocation = zipOrJsonUpload('Google Takeout location');+// Browser history ships as a Takeout Chrome `History.json` (or the whole ZIP) —+// same ZIP-or-JSON shape as the other Takeout importers.+const uploadBrowserHistory = zipOrJsonUpload('Chrome browser history');// 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', {@@ -150,4 +154,10 @@ router.post('/import/whatsapp', uploadWhatsapp, importHandler(importWhatsappHisttoOptions: (body) => ({ dryRun: body.preview, yourName: body.yourName ?? null }),}));+// POST /api/timeline/import/browser — bulk-backfill a Google Takeout Chrome+// `History.json` (standalone or the whole ZIP) → web.visit events under source+// `browser` (dedupe on a content hash of visit-instant + URL, since the export+// carries no visit id). Subframe (iframe) loads are dropped as noise.+router.post('/import/browser', uploadBrowserHistory, importHandler(importBrowserHistory));+export default router;diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.jsindex 9c314010b8..d899b3568a 100644--- a/server/routes/timeline.test.js+++ b/server/routes/timeline.test.js@@ -49,6 +49,17 @@ vi.mock('../services/whatsappImport.js', () => ({})),}));+vi.mock('../services/browserHistoryImport.js', () => ({+ importBrowserHistory: vi.fn(async (file, opts) => ({+ dryRun: Boolean(opts?.dryRun),+ parsed: 4,+ mapped: 2,+ recorded: opts?.dryRun ? 0 : 2,+ skipped: opts?.dryRun ? 0 : 2,+ summary: { visits: 2, uniqueHosts: 2, from: null, to: null, topHosts: [] },+ })),+}));+vi.mock('../services/humanActivity.js', () => ({getDaySummary: vi.fn(async () => ({ date: '2026-07-07', events: [] })),listEvents: vi.fn(async () => []),@@ -58,6 +69,7 @@ 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 { importBrowserHistory } from '../services/browserHistoryImport.js';import timelineRoutes from './timeline.js';function makeApp() {@@ -315,4 +327,42 @@ describe('timeline import routes', () => {expect(r.status).toBe(400);expect(importWhatsappHistory).not.toHaveBeenCalled();});++ it('POST /import/browser parses a History.json upload and calls the importer', async () => {+ const { boundary, body } = multipart(+ { preview: 'false' },+ { filename: 'History.json', contentType: 'application/json', content: '{"Browser History":[]}' },+ );+ const r = await request(app).post('/api/timeline/import/browser')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ recorded: 2, mapped: 2 });+ expect(importBrowserHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false });+ });++ it('browser honors preview=true as a dry run', async () => {+ const { boundary, body } = multipart(+ { preview: 'true' },+ { filename: 'Takeout.zip', contentType: 'application/zip', content: 'PK\x03\x04zip' },+ );+ const r = await request(app).post('/api/timeline/import/browser')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ dryRun: true, recorded: 0 });+ expect(importBrowserHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });+ });++ it('browser rejects a disallowed file type with 400', async () => {+ const { boundary, body } = multipart(+ {},+ { filename: 'history.txt', contentType: 'text/plain', content: 'nope' },+ );+ const r = await request(app).post('/api/timeline/import/browser')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(body);+ expect(r.status).toBe(400);+ expect(importBrowserHistory).not.toHaveBeenCalled();+ });});diff --git a/server/services/browserHistoryImport.js b/server/services/browserHistoryImport.jsnew file mode 100644index 0000000000..33e0cb4a67--- /dev/null+++ b/server/services/browserHistoryImport.js@@ -0,0 +1,249 @@+/**+ * Browser history importer (#2160) — bulk historical backfill into the+ * human-activity timeline.+ *+ * Chrome/Edge (and any Chromium browser) have no in-app "export history" button,+ * but Google Takeout ships the full history as JSON: the "Chrome" product export+ * contains `Chrome/History.json` (older vintages name it `BrowserHistory.json`)+ * whose shape is:+ *+ * { "Browser History": [+ * { "page_transition": "LINK", "title": "Example",+ * "url": "https://example.com/", "client_id": "…",+ * "time_usec": 1699999999000000 },+ * …+ * ] }+ *+ * `time_usec` is MICROSECONDS since the Unix epoch (UTC) — Takeout normalizes the+ * raw Chrome 1601-epoch value for us, so we just divide by 1000 for ms. Each entry+ * maps to a `web.visit` activity event under source `browser`. The full URL lands+ * in the row's `url` column; the summary keeps only the hostname (privacy+ * contract — no query strings in the preview line, the full URL stays in `url`).+ *+ * Subframe navigations (`AUTO_SUBFRAME` / `MANUAL_SUBFRAME` — ad/embed iframe+ * loads Chrome records alongside real navigations) carry no autobiographical "I+ * visited this" signal, so they're dropped the same way the location importer+ * drops travel segments.+ *+ * Idempotent: a visit has no stable id in the export, so the dedupe key is a+ * content hash of (visit instant + URL). 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 { createHash } from 'crypto';+import { parseZip, collectZipEntry } from '../lib/zipStream.js';+import { shortSummary, recordEvents } from './humanActivity.js';++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).+// ---------------------------------------------------------------------------++// Resolve a Takeout `time_usec` (microseconds since the Unix epoch) to a UTC ISO+// string, or null if unparseable / non-positive. A blank/nullish/zero value has+// no usable instant. Accepts a numeric string too (Takeout sometimes stringifies+// the large integer).+export function resolveHistoryInstant(timeUsec) {+ if (timeUsec === null || timeUsec === undefined || timeUsec === '') return null;+ const n = Number(timeUsec);+ if (!Number.isFinite(n) || n <= 0) return null;+ const d = new Date(Math.round(n / 1000));+ return Number.isNaN(d.getTime()) ? null : d.toISOString();+}++// Normalize a page_transition token to an UPPER_SNAKE string, or null.+export function normalizeTransition(transition) {+ if (!transition) return null;+ const s = String(transition).trim().toUpperCase();+ return s || null;+}++// Subframe transitions are iframe/embed loads (ads, widgets), not pages the user+// navigated to — dropped as noise. Matches the two Chromium subframe types.+export function isSubframeTransition(transition) {+ const t = normalizeTransition(transition);+ return t === 'AUTO_SUBFRAME' || t === 'MANUAL_SUBFRAME';+}++// Hostname of an http(s) URL, or null for a non-web scheme (chrome://, about:,+// file:) or a malformed value. Uses URL.canParse so a bad value returns null+// instead of throwing and failing the whole import; restricting to http(s) keeps+// internal browser pages from surfacing a junk "host" (e.g. chrome://newtab →+// "newtab") in the summary line.+export function hostnameOf(url) {+ const s = String(url || '').trim();+ if (!s || !URL.canParse(s)) return null;+ const parsed = new URL(s);+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;+ return parsed.hostname || null;+}++// Map ONE raw Browser-History record to an activity candidate, or null if it+// lacks a URL / usable timestamp, or is a subframe (iframe) load.+export function historyVisitToCandidate(record) {+ if (!record || typeof record !== 'object') return null;+ const url = String(record.url ?? '').trim();+ if (!url) return null;+ const happenedAt = resolveHistoryInstant(record.time_usec ?? record.timeUsec);+ if (!happenedAt) return null;+ const transition = normalizeTransition(record.page_transition ?? record.pageTransition);+ if (isSubframeTransition(transition)) return null;++ const host = hostnameOf(url);+ const title = String(record.title ?? '').trim() || host || url;++ // No visit id in the export — hash the visit's CONTENT identity (instant + URL)+ // so re-imports collapse deterministically. Two identical URLs at the same+ // microsecond are indistinguishable in the file (and can't happen in practice),+ // so collapsing them is correct — same precedent as the location importer's+ // visit-start + place key.+ const dedupeKey = createHash('sha1')+ .update(`${happenedAt} ${url}`)+ .digest('hex')+ .slice(0, 24);++ return {+ source: 'browser',+ kind: 'web.visit',+ happenedAt,+ title,+ summary: host ? shortSummary(host) : null,+ url,+ dedupeKey: `browser:${dedupeKey}`,+ metadata: {+ host: host || null,+ transition: transition || null,+ },+ };+}++// Extract the raw Browser-History records from ONE parsed history JSON object,+// handling the `{ "Browser History": [...] }` wrapper and a bare top-level array.+// Other Takeout `History.json` keys (e.g. "Favicons") are ignored.+export function extractHistoryRecords(parsed) {+ if (Array.isArray(parsed)) return parsed;+ if (!parsed || typeof parsed !== 'object') return [];+ if (Array.isArray(parsed['Browser History'])) return parsed['Browser History'];+ if (Array.isArray(parsed.browserHistory)) return parsed.browserHistory;+ return [];+}++// Map a batch of raw records to candidates, dropping the unmappable ones.+export function browserHistoryCandidates(records = []) {+ if (!Array.isArray(records)) return [];+ return records.map(historyVisitToCandidate).filter(Boolean);+}++// Summarize a candidate batch for the import preview: visit count, unique hosts+// (domains), date range, and the most-visited domains. Pure over candidates.+export function summarizeBrowserCandidates(candidates = []) {+ const list = Array.isArray(candidates) ? candidates : [];+ let earliest = null;+ let latest = null;+ const hostCounts = 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 host = c.metadata?.host;+ if (host) hostCounts.set(host, (hostCounts.get(host) || 0) + 1);+ }+ const topHosts = [...hostCounts.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ .map(([name, count]) => ({ name, count }));+ return {+ visits: list.length,+ uniqueHosts: hostCounts.size,+ from: earliest,+ to: latest,+ topHosts,+ };+}++// Parse the text of a single history JSON file into a parsed object. Throws only+// on malformed JSON; `extractHistoryRecords` handles the shape dispatch.+export function parseHistoryJsonText(text) {+ return JSON.parse(text);+}++// ---------------------------------------------------------------------------+// File ingestion (ZIP or single JSON) → raw records.+// ---------------------------------------------------------------------------++const isZip = (file) =>+ file?.mimetype === 'application/zip' ||+ file?.mimetype === 'application/x-zip-compressed' ||+ /\.zip$/i.test(file?.originalname || '');++// A Chrome history JSON member inside the Takeout ZIP: `Chrome/History.json`+// (2024+) or the older `BrowserHistory.json`. The distinctive filename lets us+// skip every other product's JSON in a full Takeout archive.+const isHistoryJsonEntry = (entryPath) =>+ /(?:^|\/)(?:Browser)?History\.json$/i.test(String(entryPath || ''));++// Extract and concatenate the raw records from every history JSON member of the+// Takeout ZIP. Non-matching entries are drained and ignored.+async function readRecordsFromZip(filePath) {+ const 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) => {+ if (isHistoryJsonEntry(entry.path)) {+ reads.push(+ collectZipEntry(entry)+ .then((buf) => {+ for (const r of extractHistoryRecords(parseHistoryJsonText(buf.toString('utf-8')))) records.push(r);+ })+ .catch(settle(reject)),+ );+ } else {+ entry.autodrain();+ }+ })+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))+ .on('error', settle(reject));+ });+ return records;+}++// Read raw history records from an uploaded file (ZIP export or single JSON).+export async function readBrowserHistoryRecords(file) {+ if (!file?.path) return [];+ if (isZip(file)) return readRecordsFromZip(file.path);+ const text = await readFile(file.path, 'utf-8');+ return extractHistoryRecords(parseHistoryJsonText(text));+}++// 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 importBrowserHistory(file, { dryRun = false } = {}) {+ const records = await readBrowserHistoryRecords(file);+ const candidates = browserHistoryCandidates(records);+ const summary = summarizeBrowserCandidates(candidates);+ if (dryRun) {+ console.log(`🌐 Browser history import preview: ${candidates.length} visit(s) from ${records.length} record(s)`);+ return { dryRun: true, parsed: records.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };+ }+ const { recorded, skipped } = await recordEvents(candidates);+ console.log(`🌐 Browser history import: ${recorded} new visit(s) recorded, ${skipped} duplicate/invalid (from ${records.length} record(s))`);+ return { dryRun: false, parsed: records.length, mapped: candidates.length, recorded, skipped, summary };+}diff --git a/server/services/browserHistoryImport.test.js b/server/services/browserHistoryImport.test.jsnew file mode 100644index 0000000000..0d431c5201--- /dev/null+++ b/server/services/browserHistoryImport.test.js@@ -0,0 +1,161 @@+import { describe, it, expect } from 'vitest';+import {+ resolveHistoryInstant,+ normalizeTransition,+ isSubframeTransition,+ hostnameOf,+ historyVisitToCandidate,+ extractHistoryRecords,+ browserHistoryCandidates,+ summarizeBrowserCandidates,+ parseHistoryJsonText,+} from './browserHistoryImport.js';++// A Google Takeout Chrome `History.json` export.+const historyFile = {+ 'Browser History': [+ {+ page_transition: 'LINK',+ title: 'Example Domain',+ url: 'https://example.com/page?q=1',+ client_id: 'abc',+ time_usec: 1614624300000000, // 2021-03-01T18:45:00Z+ },+ {+ page_transition: 'TYPED',+ title: 'News',+ url: 'https://news.example.org/story',+ time_usec: 1614624400000000,+ },+ // A subframe (iframe/ad) load — must be dropped.+ {+ page_transition: 'AUTO_SUBFRAME',+ title: 'Ad frame',+ url: 'https://ads.example.net/frame',+ time_usec: 1614624500000000,+ },+ // No URL — must be dropped.+ { page_transition: 'LINK', title: 'orphan', time_usec: 1614624600000000 },+ ],+ Favicons: [{ url: 'https://example.com/favicon.ico' }], // ignored key+};++describe('resolveHistoryInstant', () => {+ it('converts epoch microseconds to a UTC ISO string', () => {+ expect(resolveHistoryInstant(1614624300000000)).toBe('2021-03-01T18:45:00.000Z');+ });+ it('accepts a numeric string', () => {+ expect(resolveHistoryInstant('1614624300000000')).toBe('2021-03-01T18:45:00.000Z');+ });+ it('returns null for nullish / blank / non-positive values', () => {+ expect(resolveHistoryInstant(null)).toBeNull();+ expect(resolveHistoryInstant(undefined)).toBeNull();+ expect(resolveHistoryInstant('')).toBeNull();+ expect(resolveHistoryInstant(0)).toBeNull();+ expect(resolveHistoryInstant(-5)).toBeNull();+ expect(resolveHistoryInstant('nope')).toBeNull();+ });+});++describe('normalizeTransition / isSubframeTransition', () => {+ it('upper-snakes a transition token', () => {+ expect(normalizeTransition('link')).toBe('LINK');+ expect(normalizeTransition(' auto_subframe ')).toBe('AUTO_SUBFRAME');+ expect(normalizeTransition('')).toBeNull();+ expect(normalizeTransition(null)).toBeNull();+ });+ it('flags subframe transitions only', () => {+ expect(isSubframeTransition('AUTO_SUBFRAME')).toBe(true);+ expect(isSubframeTransition('manual_subframe')).toBe(true);+ expect(isSubframeTransition('LINK')).toBe(false);+ expect(isSubframeTransition(null)).toBe(false);+ });+});++describe('hostnameOf', () => {+ it('extracts the hostname', () => {+ expect(hostnameOf('https://news.example.org/story?x=1')).toBe('news.example.org');+ });+ it('returns null for unparseable / non-http values', () => {+ expect(hostnameOf('not a url')).toBeNull();+ expect(hostnameOf('')).toBeNull();+ expect(hostnameOf(null)).toBeNull();+ // chrome://newtab parses but has no hostname+ expect(hostnameOf('chrome://newtab/')).toBeNull();+ });+});++describe('historyVisitToCandidate', () => {+ it('maps a normal visit to a web.visit candidate', () => {+ const c = historyVisitToCandidate(historyFile['Browser History'][0]);+ expect(c).toMatchObject({+ source: 'browser',+ kind: 'web.visit',+ happenedAt: '2021-03-01T18:45:00.000Z',+ title: 'Example Domain',+ summary: 'example.com',+ url: 'https://example.com/page?q=1',+ });+ expect(c.dedupeKey).toMatch(/^browser:[0-9a-f]{24}$/);+ expect(c.metadata).toMatchObject({ host: 'example.com', transition: 'LINK' });+ });+ it('drops subframe loads', () => {+ expect(historyVisitToCandidate(historyFile['Browser History'][2])).toBeNull();+ });+ it('drops records without a URL', () => {+ expect(historyVisitToCandidate(historyFile['Browser History'][3])).toBeNull();+ });+ it('drops records without a usable timestamp', () => {+ expect(historyVisitToCandidate({ url: 'https://x.com', time_usec: 0 })).toBeNull();+ });+ it('falls back to the hostname when the title is empty', () => {+ const c = historyVisitToCandidate({ url: 'https://only.example/', time_usec: 1614624300000000 });+ expect(c.title).toBe('only.example');+ });+ it('produces a stable dedupe key for the same instant + URL', () => {+ const rec = { url: 'https://a.com/', time_usec: 1614624300000000, page_transition: 'LINK' };+ expect(historyVisitToCandidate(rec).dedupeKey).toBe(historyVisitToCandidate(rec).dedupeKey);+ });+});++describe('extractHistoryRecords', () => {+ it('reads the "Browser History" wrapper', () => {+ expect(extractHistoryRecords(historyFile)).toHaveLength(4);+ });+ it('reads a bare top-level array', () => {+ expect(extractHistoryRecords([{ url: 'x' }])).toHaveLength(1);+ });+ it('returns [] for non-object / missing shapes', () => {+ expect(extractHistoryRecords(null)).toEqual([]);+ expect(extractHistoryRecords({})).toEqual([]);+ expect(extractHistoryRecords(42)).toEqual([]);+ });+});++describe('browserHistoryCandidates + summarizeBrowserCandidates', () => {+ it('maps a file, dropping subframe + url-less records', () => {+ const candidates = browserHistoryCandidates(extractHistoryRecords(historyFile));+ expect(candidates).toHaveLength(2); // LINK + TYPED; subframe & url-less dropped+ expect(candidates.map((c) => c.kind)).toEqual(['web.visit', 'web.visit']);+ });+ it('summarizes counts, unique hosts, range, and top hosts', () => {+ const candidates = browserHistoryCandidates(extractHistoryRecords(historyFile));+ const summary = summarizeBrowserCandidates(candidates);+ expect(summary.visits).toBe(2);+ expect(summary.uniqueHosts).toBe(2);+ expect(summary.from).toBe('2021-03-01T18:45:00.000Z');+ expect(summary.to).toBe('2021-03-01T18:46:40.000Z');+ expect(summary.topHosts).toEqual(+ expect.arrayContaining([{ name: 'example.com', count: 1 }, { name: 'news.example.org', count: 1 }]),+ );+ });+ it('returns an empty summary for no candidates', () => {+ expect(summarizeBrowserCandidates([])).toMatchObject({ visits: 0, uniqueHosts: 0, from: null, to: null });+ });+});++describe('parseHistoryJsonText', () => {+ it('round-trips through JSON', () => {+ expect(parseHistoryJsonText(JSON.stringify(historyFile))['Browser History']).toHaveLength(4);+ });+});