Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

review: cleanup temp-file leaks, dedupe fallback identity, stale-response guard (#2160)

Adam Eivyff2f60888d04
diff --git a/client/src/components/timeline/SpotifyImportPanel.jsx b/client/src/components/timeline/SpotifyImportPanel.jsx
index 9bfab13dcd..dc2fc41812 100644
--- a/client/src/components/timeline/SpotifyImportPanel.jsx
+++ b/client/src/components/timeline/SpotifyImportPanel.jsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, useRef } from 'react';
import { Music, Upload, Loader2, CheckCircle2 } from 'lucide-react';
import * as api from '../../services/api';
import toast from '../ui/Toast';
@@ -15,40 +15,49 @@ export default function SpotifyImportPanel({ onImported }) {
const [busy, setBusy] = useState(false);
const [preview, setPreview] = useState(null);
const [result, setResult] = useState(null);
+ // Monotonic request id — a response only applies if it's still the latest
+ // request, so swapping the file mid-flight can't let a stale response land on
+ // the new selection.
+ const reqIdRef = useRef(0);
- const reset = () => { setFile(null); setPreview(null); setResult(null); };
+ const reset = () => { reqIdRef.current += 1; setFile(null); setPreview(null); setResult(null); };
const pickFile = (e) => {
const next = e.target.files?.[0] || null;
+ reqIdRef.current += 1; // invalidate any in-flight response for the old file
setFile(next);
setPreview(null);
setResult(null);
};
const runPreview = () => {
- if (!file) return;
+ if (!file || busy) return;
+ const rid = ++reqIdRef.current;
setBusy(true);
setResult(null);
api.importSpotifyHistory(file, { preview: true, silent: true })
.then((res) => {
+ if (rid !== reqIdRef.current) return;
setPreview(res);
if (!res.mapped) toast.error('No listening records found in that file.');
})
- .catch((err) => toast.error(`Preview failed: ${err.message}`))
- .finally(() => setBusy(false));
+ .catch((err) => { if (rid === reqIdRef.current) toast.error(`Preview failed: ${err.message}`); })
+ .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
};
const runImport = () => {
- if (!file) return;
+ if (!file || busy) return;
+ const rid = ++reqIdRef.current;
setBusy(true);
api.importSpotifyHistory(file, { preview: false, silent: true })
.then((res) => {
+ if (rid !== reqIdRef.current) return;
setResult(res);
toast.success(`Imported ${res.recorded} play(s) (${res.skipped} already present).`);
if (res.recorded > 0) onImported?.();
})
- .catch((err) => toast.error(`Import failed: ${err.message}`))
- .finally(() => setBusy(false));
+ .catch((err) => { if (rid === reqIdRef.current) toast.error(`Import failed: ${err.message}`); })
+ .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
};
const dateRange = (from, to) => {
@@ -81,10 +90,10 @@ export default function SpotifyImportPanel({ onImported }) {
</p>
<div className="flex flex-wrap items-center gap-2">
- <label className="inline-flex cursor-pointer items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 hover:border-port-accent">
+ <label className={`inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 ${busy ? 'cursor-not-allowed opacity-40' : 'cursor-pointer hover:border-port-accent'}`}>
<Upload size={14} />
<span>{file ? 'Change file' : 'Choose file'}</span>
- <input type="file" accept=".zip,.json,application/zip,application/json" onChange={pickFile} className="hidden" />
+ <input type="file" accept=".zip,.json,application/zip,application/json" onChange={pickFile} disabled={busy} className="hidden" />
</label>
{file && <span className="truncate text-xs text-gray-400">{file.name}</span>}
</div>
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
index 92e54d8621..aeabbcb2ea 100644
--- a/server/routes/timeline.js
+++ b/server/routes/timeline.js
@@ -66,11 +66,15 @@ router.get('/events', asyncHandler(async (req, res) => {
// import is idempotent (dedupe on played-at + track), so re-imports are safe.
// The uploaded temp file is always unlinked, whether the import succeeds or not.
router.post('/import/spotify', uploadSpotify, asyncHandler(async (req, res) => {
- const { preview } = validateRequest(importBodySchema, req.body);
const file = req.file;
if (!file?.path) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
- const result = await importSpotifyHistory(file, { dryRun: preview })
- .finally(() => unlink(file.path).catch(() => {}));
+ // Wrap BOTH validation and the import in the cleanup chain — a rejected
+ // `preview` value must still unlink the already-staged temp upload.
+ const run = async () => {
+ const { preview } = validateRequest(importBodySchema, req.body);
+ return importSpotifyHistory(file, { dryRun: preview });
+ };
+ const result = await run().finally(() => unlink(file.path).catch(() => {}));
res.json(result);
}));
diff --git a/server/services/spotifyImport.js b/server/services/spotifyImport.js
index 082e3ccb76..8fb345049f 100644
--- a/server/services/spotifyImport.js
+++ b/server/services/spotifyImport.js
@@ -78,7 +78,11 @@ export function spotifyRecordToCandidate(record) {
// Dedupe on the play instant + track identity. Two plays of the same track at
// the exact same second are indistinguishable in the export, so collapsing
// them is correct (and matches the design's "played_at + track id" contract).
- const identity = uri || title;
+ // Legacy/local records carry no URI — fall back to artist+album+title (or the
+ // show for episodes) so two *different* tracks that happen to share a title at
+ // the same instant don't wrongly collapse into one play.
+ const identity = uri
+ || [artist, isEpisode ? showName : album, title].filter(Boolean).join('|');
const dedupeKey = `spotify:${identity}:${happenedAt}`;
const summaryParts = isEpisode
@@ -182,13 +186,16 @@ async function readRecordsFromZip(filePath) {
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);
};
- const src = createReadStream(filePath);
- const parser = parseZip();
src.on('error', settle(reject));
src
.pipe(parser)
diff --git a/server/services/spotifyImport.test.js b/server/services/spotifyImport.test.js
index ae3ff6640b..daebe79c62 100644
--- a/server/services/spotifyImport.test.js
+++ b/server/services/spotifyImport.test.js
@@ -96,6 +96,15 @@ describe('spotifyRecordToCandidate', () => {
expect(c1.dedupeKey).toBe('spotify:spotify:track:2gjHtqrEnMBmD3lBWJUp2P:2023-05-01T18:30:00.000Z');
});
+ it('gives URI-less records an artist+album+title fallback identity (no title-only collapse)', () => {
+ const base = { endTime: '2022-01-15 09:05', trackName: 'Intro', msPlayed: 1000 };
+ const a = spotifyRecordToCandidate({ ...base, artistName: 'Band A', albumName: 'X' });
+ const b = spotifyRecordToCandidate({ ...base, artistName: 'Band B', albumName: 'Y' });
+ // Same title + same instant, different artists — must NOT share a dedupe key.
+ expect(a.dedupeKey).not.toBe(b.dedupeKey);
+ expect(a.dedupeKey).toContain('Band A');
+ });
+
it('classifies podcast episodes and uses the show name as summary', () => {
const c = spotifyRecordToCandidate({
ts: '2023-06-01T12:00:00Z',