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

address review (codex): never overwrite a corrupt song store, index projection, import/attachment state fixes

[._.]/ Adam Eivy91e5a80c4e4a
diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsx
index 191e664d4c..a0f5310674 100644
--- a/client/src/pages/SongBookImport.jsx
+++ b/client/src/pages/SongBookImport.jsx
@@ -14,7 +14,7 @@
* createSong → navigate to the new song's viewer.
*/
-import { useMemo, useRef, useState, useCallback } from 'react';
+import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { ListMusic, ArrowLeft, ClipboardPaste, Eraser, Wand2, Globe, FileText, Save } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -126,6 +126,18 @@ export default function SongBookImport() {
// The active tab's content → what Save will store.
const contentText = tab === 'url' ? (fetched?.content?.text || '') : normalized;
const fetchedFormat = fetched?.content?.format;
+
+ // Switching tabs switches WHICH draft Save submits — re-apply that draft's
+ // metadata so auto-filled title/artist follow the active source instead of
+ // saving tab A's metadata onto tab B's content. Refs keep the effect keyed
+ // on the tab alone (meta changes apply at their own paste/fetch sites).
+ const activeMetaRef = useRef({});
+ activeMetaRef.current = tab === 'url'
+ ? { title: fetched?.title, artist: fetched?.artist }
+ : { title: pasteMeta?.title, artist: pasteMeta?.artist };
+ useEffect(() => {
+ applyMetaDefaults(activeMetaRef.current);
+ }, [tab, applyMetaDefaults]);
// Memoized on its real inputs so detectFormat (a full line-classifier pass)
// doesn't re-run on every unrelated keystroke (title/artist/tags).
const contentFormat = useMemo(
diff --git a/client/src/pages/SongBookImport.test.jsx b/client/src/pages/SongBookImport.test.jsx
index 909e4473ba..f86e15fa9a 100644
--- a/client/src/pages/SongBookImport.test.jsx
+++ b/client/src/pages/SongBookImport.test.jsx
@@ -82,6 +82,31 @@ describe('SongBookImport', () => {
expect(title.value).toBe('My Own Name');
});
+ it('switching tabs re-applies the active draft metadata to auto-filled fields', async () => {
+ api.importSongFromUrl.mockResolvedValue({
+ draft: { title: 'Url Song', artist: 'Url Artist', content: { format: 'tab', text: 'C G' }, sourceUrl: 'https://example.com/t' },
+ });
+ renderPage();
+ const title = screen.getByLabelText('Title');
+
+ // Paste tab fills from ChordPro meta.
+ const textarea = screen.getByLabelText('Pasted tab content');
+ fireEvent.change(textarea, { target: { value: '{title: Paste Song}\nC G' } });
+ fireEvent.blur(textarea);
+ await waitFor(() => expect(title.value).toBe('Paste Song'));
+
+ // Fetch on the URL tab — its meta takes over while that tab is active.
+ fireEvent.click(screen.getByRole('tab', { name: 'From URL' }));
+ fireEvent.change(screen.getByLabelText('Tab / chord-sheet URL'), { target: { value: 'https://example.com/t' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Fetch' }));
+ await waitFor(() => expect(title.value).toBe('Url Song'));
+
+ // Back to paste — Save would submit the PASTED content, so the auto-fill
+ // must follow it back instead of keeping the URL song's metadata.
+ fireEvent.click(screen.getByRole('tab', { name: 'Paste' }));
+ await waitFor(() => expect(title.value).toBe('Paste Song'));
+ });
+
it('sends an in-range pasted capo through unchanged', async () => {
renderPage();
fireEvent.change(screen.getByLabelText('Pasted tab content'), {
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index ac11e8419e..7f2f3269a9 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -136,7 +136,10 @@ export default function SongBookViewer() {
if (!cancelled && !attachmentsMutatedRef.current) setAttachments(Array.isArray(list) ? list : []);
})
.catch(() => {
- if (!cancelled && !attachmentsMutatedRef.current) setAttachments([]);
+ // Presence lookup failed — don't render "no attachments" over synced
+ // metadata that exists. Fall back to the record's own list with
+ // presence unknown (no "not on this machine" pill either way).
+ if (!cancelled && !attachmentsMutatedRef.current) setAttachments('failed');
});
return () => { cancelled = true; };
}, [id, retryKey]);
@@ -168,6 +171,11 @@ export default function SongBookViewer() {
// --- Autoscroll + wake lock
const scrollRef = useRef(null);
const { playing, toggle, stop, pxPerSec, setPxPerSec } = useAutoscroll(scrollRef);
+
+ // Presence lookup failed → show the record's own synced metadata with
+ // presence unknown (rendered as plain links; only an explicit present:false
+ // gets the "not on this machine" pill), never a false "No attachments".
+ const shownAttachments = attachments === 'failed' ? (song?.attachments || []) : (attachments || []);
useWakeLock(playing);
const scrollToTop = useCallback(() => {
@@ -342,7 +350,10 @@ export default function SongBookViewer() {
) : (
<button
type="button"
- onClick={() => setMode('edit')}
+ // Explicitly stop autoscroll before the play-mode scroll node
+ // unmounts (the detached-element bottom check would also stop
+ // it, but deterministic beats incidental).
+ onClick={() => { stop(); setMode('edit'); }}
className={btnClass}
>
<Pencil size={15} />
@@ -592,13 +603,13 @@ export default function SongBookViewer() {
</div>
{attachments === null ? (
<p className="text-xs text-gray-500">Loading attachments…</p>
- ) : attachments.length === 0 ? (
+ ) : shownAttachments.length === 0 ? (
<p className="text-xs text-gray-500">No attachments — upload sheet-music PDFs, images, or MIDI files.</p>
) : (
<ul className="space-y-1">
- {attachments.map((att) => (
+ {shownAttachments.map((att) => (
<li key={att.filename} className="flex items-center gap-3 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm">
- {att.present ? (
+ {att.present !== false ? (
<a
href={songAttachmentUrl(id, att.filename)}
target="_blank"
diff --git a/scripts/migrations/190-seed-songbook-songs.js b/scripts/migrations/190-seed-songbook-songs.js
index 5c50c04b36..012af3ab0b 100644
--- a/scripts/migrations/190-seed-songbook-songs.js
+++ b/scripts/migrations/190-seed-songbook-songs.js
@@ -11,23 +11,31 @@
* Idempotent and non-destructive: a seed id already present in the live store
* — a user-edited copy, a synced copy from a peer, or a tombstone from a
* deliberate delete — is NEVER overwritten (so a deleted seed stays deleted).
- * The file is written only when at least one record was added. The seeds carry
- * no originInstanceId; brainStorage's boot-time backfill stamps it, exactly as
- * it does for the setup-data copy path.
+ * The file is written only when at least one record was added, and NEVER when
+ * the existing file is unreadable (corrupt JSON is possibly-recoverable user
+ * data — seeds are not worth destroying it). The seeds carry a fixed
+ * originInstanceId ('seed') so every install holds byte-identical records and
+ * the brain reconcile checksum converges across peers.
*/
import { readFile, writeFile, mkdir } from 'fs/promises';
import { join, dirname } from 'path';
-// tryReadFile convention: missing/unreadable → fallback (the migration runner
-// executes before the service layer is wired, so no server/lib imports here).
-async function readJsonOr(path, fallback) {
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (raw == null) return fallback;
+// Tagged read: 'missing' (ENOENT — safe to treat as an empty store) is NOT the
+// same as 'invalid' (file exists but won't parse — possibly recoverable user
+// data that a write here would irreversibly destroy). The migration runner
+// executes before the service layer is wired, so no server/lib imports here.
+async function readJsonTagged(path) {
+ let raw;
try {
- return JSON.parse(raw);
- } catch {
- return fallback;
+ raw = await readFile(path, 'utf-8');
+ } catch (err) {
+ return err?.code === 'ENOENT' ? { state: 'missing' } : { state: 'invalid', error: err?.message };
+ }
+ try {
+ return { state: 'ok', doc: JSON.parse(raw) };
+ } catch (err) {
+ return { state: 'invalid', error: err?.message };
}
}
@@ -35,7 +43,8 @@ export async function up({ rootDir }) {
const seedPath = join(rootDir, 'data.reference', 'brain', 'songs.json');
const livePath = join(rootDir, 'data', 'brain', 'songs.json');
- const seed = await readJsonOr(seedPath, null);
+ const seedRead = await readJsonTagged(seedPath);
+ const seed = seedRead.state === 'ok' ? seedRead.doc : null;
const seedRecords = seed?.records && typeof seed.records === 'object' ? seed.records : {};
const seedIds = Object.keys(seedRecords);
if (seedIds.length === 0) {
@@ -43,7 +52,15 @@ export async function up({ rootDir }) {
return { ok: true, reason: 'no-seeds' };
}
- const live = await readJsonOr(livePath, { records: {} });
+ const liveRead = await readJsonTagged(livePath);
+ if (liveRead.state === 'invalid') {
+ // The live store exists but won't parse — writing seeds over it would turn
+ // a recoverable corrupt file into permanent data loss. Leave it untouched;
+ // the seeds are cosmetic starter content, not worth risking user data.
+ console.error(`❌ songbook-seed: data/brain/songs.json exists but is unreadable (${liveRead.error}) — leaving it untouched; repair or remove it to receive the starter songs.`);
+ return { ok: true, reason: 'live-store-unreadable' };
+ }
+ const live = liveRead.state === 'ok' ? liveRead.doc : { records: {} };
if (!live.records || typeof live.records !== 'object') live.records = {};
let added = 0;
diff --git a/scripts/migrations/190-seed-songbook-songs.test.js b/scripts/migrations/190-seed-songbook-songs.test.js
index 7b4b77952f..8fc5e8d83f 100644
--- a/scripts/migrations/190-seed-songbook-songs.test.js
+++ b/scripts/migrations/190-seed-songbook-songs.test.js
@@ -98,13 +98,15 @@ describe('migration 190 — seed songbook songs', () => {
expect(empty.reason).toBe('no-seeds');
});
- it('treats an unreadable live file as an empty store', async () => {
+ it('NEVER writes over an unreadable live file — corrupt user data beats seeds', async () => {
writeSeed();
mkdirSync(liveDir, { recursive: true });
writeFileSync(join(liveDir, 'songs.json'), '{not json');
const result = await migration.up({ rootDir });
- expect(result.added).toBe(2);
- expect(Object.keys(readLive().records)).toHaveLength(2);
+ expect(result.reason).toBe('live-store-unreadable');
+ expect(result.added).toBeUndefined();
+ // The corrupt file is byte-for-byte untouched (recoverable by the user).
+ expect(readFileSync(join(liveDir, 'songs.json'), 'utf-8')).toBe('{not json');
});
it('seeds the SHIPPED reference records against a real repo layout shape', async () => {
diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.js
index 438c448d9f..8c8af3f18a 100644
--- a/server/routes/brainSongbook.js
+++ b/server/routes/brainSongbook.js
@@ -89,7 +89,13 @@ router.post('/import/url', asyncHandler(async (req, res) => {
// =============================================================================
router.get('/', asyncHandler(async (req, res) => {
- const songs = await brainStorage.getAll('songs');
+ // Index projection: the list view needs metadata only, and content.text can
+ // be 200k chars per song — a large repertoire would ship megabytes nobody
+ // reads. The full record (with text) comes from GET /:id.
+ const songs = (await brainStorage.getAll('songs')).map(({ content, ...rest }) => ({
+ ...rest,
+ content: { format: content?.format || 'tab' },
+ }));
res.json({ songs });
}));
diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.js
index bd70fa4f37..b0b00b3f4b 100644
--- a/server/routes/brainSongbook.test.js
+++ b/server/routes/brainSongbook.test.js
@@ -109,6 +109,15 @@ describe('Brain SongBook routes', () => {
expect(res.body.songs).toHaveLength(1);
expect(brainStorage.getAll).toHaveBeenCalledWith('songs');
});
+
+ it('projects out content.text — the index is metadata-only, text comes from GET /:id', async () => {
+ const song = baseSong();
+ song.content = { format: 'chordpro', text: 'x'.repeat(5000) };
+ brainStorage.getAll.mockResolvedValue([song]);
+ const res = await request(app).get('/api/brain/songbook');
+ expect(res.body.songs[0].content).toEqual({ format: 'chordpro' });
+ expect(res.body.songs[0].title).toBe(song.title);
+ });
});
describe('GET /api/brain/songbook/:id', () => {