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
refactor: centralize streaming ZIP import lifecycle across import services (#2373)
Adam Eivy18cfbbdfe09a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ad9334adbe..7f236f690c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -28,6 +28,8 @@## Changed+- **[issue-2373] The six data-import services now share one streaming-ZIP lifecycle helper instead of each re-implementing it.** browserHistory, spotify, youtube, whatsapp, takeoutLocation, and discord all repeated the same ZIP predicate plus a hand-rolled `createReadStream → parseZip` lifecycle (single-settle guard, source/parser teardown on early failure, autodrain of skipped members, per-entry promise collection, and close/error coordination). That is now centralized in `server/lib/zipStream.js` as `isZipUpload(file)` and `collectZipEntries(path, { match, onMatch, maxBytes? })` — which owns teardown, autodrain, and awaiting every matching entry's work — leaving each importer with only its domain match/parse callbacks. No behavior change; covered by new failure / truncated-archive / corrupt-member regression tests.+- **CoS scheduled tasks get a day-of-week + time-of-day picker — no more typing crontab syntax for weekly schedules.** Every CoS cron surface (Schedule tab overrides and global config, the Workflow/Timeline schedule editor's pinned-time mode, CoS system jobs, and per-app custom tasks) now leads with a row of day pills (S M T W T F S) plus a time input: click the days it should run and set the time, and the cron expression is built for you (no days selected = every day). The raw crontab field and presets are still there behind an "Advanced" toggle for interval/stepped schedules the picker can't represent, and it round-trips — an existing `0 9 * * 1,3` lights up Mon/Wed at 09:00. Built on a shared `WeekdayTimePicker` component and `parseSimpleCron`/`buildWeeklyCron` helpers so all surfaces stay consistent.- **Creative Director is now a top-level page under Create, not a Media Gen tab.** It moved out of the Media Gen tab strip to its own `/creative-director` route with a Create sidebar link, so it's reachable directly (⌘K, voice nav, and the sidebar) without first opening Media Gen. Legacy `/media/creative-director` links and deep-links (including `:id/:tab`) redirect to the new route, preserving query string and hash.diff --git a/server/lib/README.md b/server/lib/README.mdindex d740cdd1d3..22abaa99b1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -129,7 +129,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `multipart.js` | Streaming multipart/form-data parser. || `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. || `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |-| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |+| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `collectZipEntries(path, { match, onMatch, maxBytes? })` owns the multi-entry import lifecycle (teardown, autodrain, per-entry await) leaving callers only match/parse; `isZipUpload(file)` predicate for an uploaded ZIP; `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. || `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. || `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. `sidecarGenParamsHash` canonically hashes a sidecar's gen-params (excludes the machine-local `sha256` cache block) for cross-machine sidecar-convergence comparisons. |diff --git a/server/lib/zipStream.js b/server/lib/zipStream.jsindex 6d57200bca..a0d7ca60b0 100644--- a/server/lib/zipStream.js+++ b/server/lib/zipStream.js@@ -237,6 +237,78 @@ export function collectZipEntry(entry, maxBytes = MAX_ZIP_MEMBER_BYTES) {});}+/**+ * Predicate for "this uploaded file is a ZIP archive." Every import service that+ * accepts either a raw export ZIP or a single unpacked JSON/CSV/TXT member shared+ * this exact three-way check (mimetype `application/zip`, the Windows-y+ * `application/x-zip-compressed`, or a `.zip` filename). Nullish-safe: a missing+ * `file`, `mimetype`, or `originalname` returns false rather than throwing.+ */+export function isZipUpload(file) {+ return (+ file?.mimetype === 'application/zip' ||+ file?.mimetype === 'application/x-zip-compressed' ||+ /\.zip$/i.test(file?.originalname || '')+ );+}++/**+ * Stream a ZIP from disk and hand every entry whose path satisfies `match` to+ * `onMatch(buffer, entryPath)` as a fully-decompressed Buffer; non-matching+ * entries are drained without inflation.+ *+ * This owns the whole multi-entry streaming lifecycle that each import service+ * (browser-history, spotify, youtube, whatsapp, takeout-location, discord)+ * otherwise re-implemented by hand: a single-settle guard, source + parser+ * teardown on the FIRST failure (so an early error in a multi-GB upload doesn't+ * keep reading to EOF), autodrain of skipped members, per-entry work collection,+ * and awaiting every matching entry's `onMatch` before resolving on `close`.+ * Resolves once every matching member has been read AND its `onMatch` settled;+ * rejects on the first source / parser / inflate / oversize / `onMatch` error.+ *+ * `match` may be a predicate `(entryPath) => boolean` (evaluated at entry-emit+ * time, so a closure over caller state — e.g. "the first non-preferred member" —+ * is honored) or a substring shorthand. `onMatch` may be sync or async and+ * accumulates into the caller's own closure (an array, a `Map`, a string). Each+ * matching member is buffered under `maxBytes` (see `collectZipEntry`), so a+ * pathological member can't exhaust RAM. Leaves the caller with ONLY its domain+ * match/parse logic.+ */+export function collectZipEntries(zipPath, { match, onMatch, maxBytes = MAX_ZIP_MEMBER_BYTES } = {}) {+ const test = typeof match === 'function' ? match : (name) => name.includes(match);+ const reads = [];+ return new Promise((resolve, reject) => {+ let settled = false;+ const src = createReadStream(zipPath);+ 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 member, corrupt/truncated 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 (test(entry.path)) {+ const entryPath = entry.path;+ reads.push(+ collectZipEntry(entry, maxBytes)+ .then((buf) => onMatch(buf, entryPath))+ .catch(settle(reject)),+ );+ } else {+ entry.autodrain();+ }+ })+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))+ .on('error', settle(reject));+ });+}+/*** Extract the first entry whose path satisfies `match` (a predicate or a* substring) from a zip on disk, resolving to its decompressed Buffer (or nulldiff --git a/server/lib/zipStream.test.js b/server/lib/zipStream.test.jsindex 095dcb8bd9..2f6289c980 100644--- a/server/lib/zipStream.test.js+++ b/server/lib/zipStream.test.js@@ -4,7 +4,7 @@ import { deflateRawSync } from 'zlib';import { writeFile, rm, mkdtemp } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';-import { parseZip, extractZipEntryToBuffer, collectZipEntry } from './zipStream.js';+import { parseZip, extractZipEntryToBuffer, collectZipEntry, isZipUpload, collectZipEntries } from './zipStream.js';const LOCAL_SIG = 0x04034b50;const CENTRAL_SIG = 0x02014b50;@@ -266,6 +266,164 @@ describe('collectZipEntry', () => {});});+describe('isZipUpload', () => {+ it('accepts application/zip mimetype', () => {+ expect(isZipUpload({ mimetype: 'application/zip' })).toBe(true);+ });++ it('accepts the Windows x-zip-compressed mimetype', () => {+ expect(isZipUpload({ mimetype: 'application/x-zip-compressed' })).toBe(true);+ });++ it('accepts a .zip filename regardless of mimetype (case-insensitive)', () => {+ expect(isZipUpload({ mimetype: 'application/octet-stream', originalname: 'export.ZIP' })).toBe(true);+ expect(isZipUpload({ originalname: 'takeout.zip' })).toBe(true);+ });++ it('rejects a non-zip upload', () => {+ expect(isZipUpload({ mimetype: 'application/json', originalname: 'history.json' })).toBe(false);+ expect(isZipUpload({ originalname: '_chat.txt' })).toBe(false);+ });++ it('is nullish-safe (missing file / fields do not throw)', () => {+ expect(isZipUpload(null)).toBe(false);+ expect(isZipUpload(undefined)).toBe(false);+ expect(isZipUpload({})).toBe(false);+ });+});++describe('collectZipEntries', () => {+ let dir;+ beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'zipentries-')); });+ afterAll(async () => { await rm(dir, { recursive: true, force: true }); });++ async function writeZip(name, buf) {+ const p = join(dir, name);+ await writeFile(p, buf);+ return p;+ }++ it('hands each matching member to onMatch and drains the rest', async () => {+ const zip = Buffer.concat([+ buildEntry('data/keep-a.json', Buffer.from('{"a":1}')),+ buildEntry('data/skip.bin', Buffer.alloc(32, 9)),+ buildEntry('data/keep-b.json', deflateRawSync(Buffer.from('{"b":2}')), { method: 8 }),+ buildEocd(),+ ]);+ const zipPath = await writeZip('mixed.zip', zip);+ const collected = [];+ await collectZipEntries(zipPath, {+ match: (p) => p.endsWith('.json'),+ onMatch: (buf, p) => { collected.push(`${p}:${buf.toString('utf-8')}`); },+ });+ expect(collected.sort()).toEqual(['data/keep-a.json:{"a":1}', 'data/keep-b.json:{"b":2}']);+ });++ it('awaits async onMatch work before resolving (close does not beat the reads)', async () => {+ const zip = Buffer.concat([+ buildEntry('a.json', Buffer.from('1')),+ buildEntry('b.json', Buffer.from('2')),+ buildEocd(),+ ]);+ const zipPath = await writeZip('async.zip', zip);+ const seen = [];+ await collectZipEntries(zipPath, {+ match: '.json',+ onMatch: async (buf) => {+ await new Promise((r) => setTimeout(r, 5));+ seen.push(buf.toString('utf-8'));+ },+ });+ expect(seen.sort()).toEqual(['1', '2']);+ });++ it('supports a match closure over caller state (whatsapp first-fallback pattern)', async () => {+ const zip = Buffer.concat([+ buildEntry('WhatsApp Chat with Bob.txt', Buffer.from('fallback body')),+ buildEntry('extra.txt', Buffer.from('second txt')),+ buildEocd(),+ ]);+ const zipPath = await writeZip('whatsapp.zip', zip);+ let preferred = null;+ let fallback = null;+ await collectZipEntries(zipPath, {+ match: (p) => /_chat\.txt$/i.test(p) || (/\.txt$/i.test(p) && fallback === null),+ onMatch: (buf, p) => {+ if (/_chat\.txt$/i.test(p)) preferred = buf.toString('utf-8');+ else if (fallback === null) fallback = buf.toString('utf-8');+ },+ });+ expect(preferred).toBeNull();+ expect(fallback).toBe('fallback body');+ });++ it('rejects (does not hang) when a matching member fails to parse in onMatch', async () => {+ const zip = Buffer.concat([+ buildEntry('good.json', Buffer.from('{"ok":true}')),+ buildEntry('bad.json', Buffer.from('{not valid json')),+ buildEocd(),+ ]);+ const zipPath = await writeZip('badmember.zip', zip);+ await expect(+ collectZipEntries(zipPath, {+ match: '.json',+ onMatch: (buf) => { JSON.parse(buf.toString('utf-8')); },+ }),+ ).rejects.toThrow();+ });++ it('rejects (does not hang) when a matching deflated member is corrupt', async () => {+ // method:8 declares deflate but the payload is garbage — the inflate pipeline+ // errors; the collector must reject rather than hang awaiting the entry.+ const zip = Buffer.concat([+ buildEntry('corrupt.json', Buffer.from('definitely not a deflate stream'), { method: 8 }),+ buildEocd(),+ ]);+ const zipPath = await writeZip('corrupt.zip', zip);+ await expect(+ collectZipEntries(zipPath, { match: '.json', onMatch: () => {} }),+ ).rejects.toThrow();+ });++ it('rejects (does not hang) when a matching member exceeds maxBytes', async () => {+ const zip = Buffer.concat([+ buildEntry('big.json', Buffer.alloc(64, 0x41)),+ buildEocd(),+ ]);+ const zipPath = await writeZip('oversize.zip', zip);+ await expect(+ collectZipEntries(zipPath, { match: '.json', onMatch: () => {}, maxBytes: 16 }),+ ).rejects.toThrow(/exceeds 16 byte limit/);+ });++ it('rejects when the source file is missing', async () => {+ await expect(+ collectZipEntries(join(dir, 'does-not-exist.zip'), { match: '.json', onMatch: () => {} }),+ ).rejects.toThrow();+ });++ it('resolves with no matches on a truncated archive whose central directory is cut off', async () => {+ // A truncated ZIP (upload interrupted): a complete stored entry followed by a+ // sliced-off second header and no EOCD. The parser reads the whole first entry+ // and simply reaches stream end — no hang, no throw, matches processed.+ const full = Buffer.concat([+ buildEntry('first.json', Buffer.from('{"n":1}')),+ buildEntry('second.json', Buffer.from('{"n":2}')),+ ]);+ // Cut mid-way through the second entry's header so it never completes.+ const truncated = full.subarray(0, full.length - 20);+ const zipPath = await writeZip('truncated.zip', truncated);+ const collected = [];+ await collectZipEntries(zipPath, {+ match: '.json',+ onMatch: (buf, p) => { collected.push(p); },+ });+ // The first entry is intact and processed; the second is never fully emitted.+ expect(collected).toContain('first.json');+ expect(collected).not.toContain('second.json');+ });+});+describe('extractZipEntryToBuffer', () => {let dir;let zipPath;diff --git a/server/services/browserHistoryImport.js b/server/services/browserHistoryImport.jsindex e2487271f9..27a6513b44 100644--- a/server/services/browserHistoryImport.js+++ b/server/services/browserHistoryImport.js@@ -33,10 +33,9 @@* 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 { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents } from './humanActivity.js';// ---------------------------------------------------------------------------@@ -181,60 +180,27 @@ export function parseHistoryJsonText(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).+// The ZIP path delegates the whole streaming lifecycle (teardown, autodrain,+// per-entry await) to `collectZipEntries`, leaving only the match/parse callbacks.export async function readBrowserHistoryRecords(file) {if (!file?.path) return [];- if (isZip(file)) return readRecordsFromZip(file.path);+ if (isZipUpload(file)) {+ const records = [];+ await collectZipEntries(file.path, {+ match: isHistoryJsonEntry,+ onMatch: (buf) => {+ for (const r of extractHistoryRecords(parseHistoryJsonText(buf.toString('utf-8')))) records.push(r);+ },+ });+ return records;+ }const text = await readFile(file.path, 'utf-8');return extractHistoryRecords(parseHistoryJsonText(text));}diff --git a/server/services/discordImport.js b/server/services/discordImport.jsindex 86b012a672..ad3c278a4b 100644--- a/server/services/discordImport.js+++ b/server/services/discordImport.js@@ -19,9 +19,8 @@* 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 { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents, normalizeParticipants } from './humanActivity.js';// ---------------------------------------------------------------------------@@ -199,11 +198,6 @@ export function summarizeDiscordCandidates(candidates = []) {// 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)`.@@ -217,51 +211,27 @@ const isChannelJsonEntry = (entryPath) => /(?:^|\/)messages\/[^/]+\/channel\.jso// 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.+// message carries its channel's context. `collectZipEntries` owns the streaming+// lifecycle (teardown, autodrain, per-entry await); the onMatch dispatches on the+// entry path since two member kinds (messages + channel metadata) are collected.async function readItemsFromZip(filePath) {const channels = new Map(); // dir → parsed channel.jsonconst 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));+ await collectZipEntries(filePath, {+ match: (entryPath) => {+ const dir = channelDirOf(entryPath);+ return Boolean(dir) && (isMessagesEntry(entryPath) || isChannelJsonEntry(entryPath));+ },+ onMatch: (buf, entryPath) => {+ const dir = channelDirOf(entryPath);+ if (isMessagesEntry(entryPath)) {+ const recs = parseDiscordMessagesText(buf.toString('utf-8'), entryPath);+ const existing = messagesByDir.get(dir) || [];+ messagesByDir.set(dir, existing.concat(recs));+ } else {+ channels.set(dir, JSON.parse(buf.toString('utf-8')));+ }+ },});const items = [];for (const [dir, recs] of messagesByDir) {@@ -276,7 +246,7 @@ async function readItemsFromZip(filePath) {// context).export async function readDiscordItems(file) {if (!file?.path) return [];- if (isZip(file)) return readItemsFromZip(file.path);+ if (isZipUpload(file)) return readItemsFromZip(file.path);const text = await readFile(file.path, 'utf-8');return parseDiscordMessagesText(text, file.originalname || '').map((record) => ({ record, channel: null }));}diff --git a/server/services/spotifyImport.js b/server/services/spotifyImport.jsindex 8fb345049f..90b185f145 100644--- a/server/services/spotifyImport.js+++ b/server/services/spotifyImport.js@@ -21,9 +21,8 @@* 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 { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents } from './humanActivity.js';// ---------------------------------------------------------------------------@@ -168,60 +167,27 @@ export function parseSpotifyJsonText(text) {// File ingestion (ZIP or single JSON) → records.// ----------------------------------------------------------------------------const isZip = (file) =>- file?.mimetype === 'application/zip' ||- file?.mimetype === 'application/x-zip-compressed' ||- /\.zip$/i.test(file?.originalname || '');-// A streaming-history JSON member inside the export ZIP. Spotify names them// `Streaming_History_Audio_2023_1.json` (extended) or `StreamingHistory0.json`// (legacy), sometimes under a `Spotify Extended Streaming History/` folder.const isHistoryJsonEntry = (entryPath) =>/(?:^|\/)(?:Streaming_History_Audio|StreamingHistory)[^/]*\.json$/i.test(entryPath);-// Extract and concatenate the play records from every streaming-history JSON-// member of the export ZIP. Non-history 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 200MB 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 parseSpotifyJsonText(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 play records from an uploaded file (ZIP export or single JSON array).+// The ZIP path delegates the whole streaming lifecycle (teardown, autodrain,+// per-entry await) to `collectZipEntries`, leaving only the match/parse callbacks.export async function readSpotifyRecords(file) {if (!file?.path) return [];- if (isZip(file)) return readRecordsFromZip(file.path);+ if (isZipUpload(file)) {+ const records = [];+ await collectZipEntries(file.path, {+ match: isHistoryJsonEntry,+ onMatch: (buf) => {+ for (const r of parseSpotifyJsonText(buf.toString('utf-8'))) records.push(r);+ },+ });+ return records;+ }const text = await readFile(file.path, 'utf-8');return parseSpotifyJsonText(text);}diff --git a/server/services/takeoutLocationImport.js b/server/services/takeoutLocationImport.jsindex 0c6f68ff13..ecf1a70ba6 100644--- a/server/services/takeoutLocationImport.js+++ b/server/services/takeoutLocationImport.js@@ -26,9 +26,8 @@* newer 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 { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents } from './humanActivity.js';// ---------------------------------------------------------------------------@@ -270,11 +269,6 @@ export function parseTakeoutJsonText(text) {// File ingestion (ZIP or single JSON) → visit intermediates.// ----------------------------------------------------------------------------const isZip = (file) =>- file?.mimetype === 'application/zip' ||- file?.mimetype === 'application/x-zip-compressed' ||- /\.zip$/i.test(file?.originalname || '');-// A semantic-location-history JSON member inside the Takeout ZIP. Google names// per-month files `2021_JANUARY.json` under a `Semantic Location History/YYYY/`// folder; the on-device export ships a single `location-history.json` /@@ -291,49 +285,21 @@ const isLocationJsonEntry = (entryPath) => {);};-// Extract and concatenate the visit intermediates from every location-history-// JSON member of the Takeout ZIP. Non-matching entries are drained and ignored.-async function readVisitsFromZip(filePath) {- const visits = [];- 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 (isLocationJsonEntry(entry.path)) {- reads.push(- collectZipEntry(entry)- .then((buf) => {- for (const v of extractVisits(parseTakeoutJsonText(buf.toString('utf-8')))) visits.push(v);- })- .catch(settle(reject)),- );- } else {- entry.autodrain();- }- })- .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))- .on('error', settle(reject));- });- return visits;-}-// Read visit intermediates from an uploaded file (ZIP export or single JSON).+// The ZIP path delegates the whole streaming lifecycle (teardown, autodrain,+// per-entry await) to `collectZipEntries`, leaving only the match/parse callbacks.export async function readTakeoutVisits(file) {if (!file?.path) return [];- if (isZip(file)) return readVisitsFromZip(file.path);+ if (isZipUpload(file)) {+ const visits = [];+ await collectZipEntries(file.path, {+ match: isLocationJsonEntry,+ onMatch: (buf) => {+ for (const v of extractVisits(parseTakeoutJsonText(buf.toString('utf-8')))) visits.push(v);+ },+ });+ return visits;+ }const text = await readFile(file.path, 'utf-8');return extractVisits(parseTakeoutJsonText(text));}diff --git a/server/services/whatsappImport.js b/server/services/whatsappImport.jsindex 6088d946fd..dfaed77c4c 100644--- a/server/services/whatsappImport.js+++ b/server/services/whatsappImport.js@@ -49,10 +49,9 @@* 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';import { createHash } from 'crypto';-import { parseZip, collectZipEntry } from '../lib/zipStream.js';+import { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents, resolveEventInstant } from './humanActivity.js';import { getUserTimezone } from '../lib/timezone.js';@@ -315,11 +314,6 @@ export function deriveChatTitle(fileName) {// File ingestion (single `.txt` or an "Export chat" ZIP) → chat text.// ----------------------------------------------------------------------------const isZip = (file) =>- file?.mimetype === 'application/zip' ||- file?.mimetype === 'application/x-zip-compressed' ||- /\.zip$/i.test(file?.originalname || '');-// The chat transcript inside an "Export chat" ZIP is `_chat.txt`; older/renamed// exports may name it `WhatsApp Chat with X.txt`. Prefer `_chat.txt`, else the// first `.txt` member.@@ -328,36 +322,17 @@ const isAnyTxtEntry = (entryPath) => /\.txt$/i.test(String(entryPath || ''));// Extract the chat transcript text from an "Export chat" ZIP. Media entries are// drained and ignored. Resolves to the transcript string ('' if none found).+// The `match` closes over `fallback` so only the preferred `_chat.txt` plus the+// first other `.txt` are collected; `collectZipEntries` owns teardown/autodrain.async function readTextFromZip(filePath) {let preferred = null; // _chat.txtlet fallback = null; // first other .txt- const reads = [];- await new Promise((resolve, reject) => {- let settled = false;- const src = createReadStream(filePath);- const parser = parseZip();- const settle = (fn) => (...args) => {- if (settled) return;- settled = true;- // On failure tear down the pipeline so a large upload with an early error- // doesn't keep reading to EOF.- if (fn === reject) { src.destroy(); parser.destroy?.(); }- fn(...args);- };- src.on('error', settle(reject));- src- .pipe(parser)- .on('entry', (entry) => {- if (isChatTxtEntry(entry.path)) {- reads.push(collectZipEntry(entry).then((buf) => { preferred = buf.toString('utf-8'); }).catch(settle(reject)));- } else if (isAnyTxtEntry(entry.path) && fallback === null) {- reads.push(collectZipEntry(entry).then((buf) => { if (fallback === null) fallback = buf.toString('utf-8'); }).catch(settle(reject)));- } else {- entry.autodrain();- }- })- .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))- .on('error', settle(reject));+ await collectZipEntries(filePath, {+ match: (entryPath) => isChatTxtEntry(entryPath) || (isAnyTxtEntry(entryPath) && fallback === null),+ onMatch: (buf, entryPath) => {+ if (isChatTxtEntry(entryPath)) preferred = buf.toString('utf-8');+ else if (fallback === null) fallback = buf.toString('utf-8');+ },});return preferred ?? fallback ?? '';}@@ -366,7 +341,7 @@ async function readTextFromZip(filePath) {// "Export chat" ZIP).export async function readWhatsappText(file) {if (!file?.path) return '';- if (isZip(file)) return readTextFromZip(file.path);+ if (isZipUpload(file)) return readTextFromZip(file.path);return readFile(file.path, 'utf-8');}diff --git a/server/services/youtubeImport.js b/server/services/youtubeImport.jsindex 7df11f6e8a..ac684e42ea 100644--- a/server/services/youtubeImport.js+++ b/server/services/youtubeImport.js@@ -28,9 +28,8 @@* `recordEvents`'s `ON CONFLICT DO NOTHING` makes re-imports (and overlap with the* scrape) no-ops. 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 { collectZipEntries, isZipUpload } from '../lib/zipStream.js';import { shortSummary, recordEvents, localDayKey } from './humanActivity.js';import { getUserTimezone } from '../lib/timezone.js';@@ -163,11 +162,6 @@ export function parseYoutubeJsonText(text) {// File ingestion (ZIP or single JSON) → records.// ----------------------------------------------------------------------------const isZip = (file) =>- file?.mimetype === 'application/zip' ||- file?.mimetype === 'application/x-zip-compressed' ||- /\.zip$/i.test(file?.originalname || '');-// The watch-history JSON member inside a Takeout ZIP. Google nests it at// `Takeout/YouTube and YouTube Music/history/watch-history.json`; match the// filename anywhere so folder-naming/vintage differences don't miss it. The HTML@@ -176,49 +170,21 @@ const isZip = (file) =>const isWatchHistoryJsonEntry = (entryPath) =>/(?:^|\/)watch-history[^/]*\.json$/i.test(String(entryPath || ''));-// Extract and concatenate the watch records from every watch-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 (isWatchHistoryJsonEntry(entry.path)) {- reads.push(- collectZipEntry(entry)- .then((buf) => {- for (const r of parseYoutubeJsonText(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 watch records from an uploaded file (ZIP export or single JSON array).+// The ZIP path delegates the whole streaming lifecycle (teardown, autodrain,+// per-entry await) to `collectZipEntries`, leaving only the match/parse callbacks.export async function readYoutubeRecords(file) {if (!file?.path) return [];- if (isZip(file)) return readRecordsFromZip(file.path);+ if (isZipUpload(file)) {+ const records = [];+ await collectZipEntries(file.path, {+ match: isWatchHistoryJsonEntry,+ onMatch: (buf) => {+ for (const r of parseYoutubeJsonText(buf.toString('utf-8'))) records.push(r);+ },+ });+ return records;+ }const text = await readFile(file.path, 'utf-8');return parseYoutubeJsonText(text);}